ExecutionContext.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. /*============================================================
  5. **
  6. **
  7. **
  8. ** Purpose: Capture execution context for a thread
  9. **
  10. **
  11. ===========================================================*/
  12. using System.Diagnostics;
  13. using System.Runtime.CompilerServices;
  14. using System.Runtime.ExceptionServices;
  15. using System.Runtime.Serialization;
  16. using Thread = Internal.Runtime.Augments.RuntimeThread;
  17. namespace System.Threading
  18. {
  19. public delegate void ContextCallback(object state);
  20. internal delegate void ContextCallback<TState>(ref TState state);
  21. public sealed class ExecutionContext : IDisposable, ISerializable
  22. {
  23. internal static readonly ExecutionContext Default = new ExecutionContext(isDefault: true);
  24. internal static readonly ExecutionContext DefaultFlowSuppressed = new ExecutionContext(AsyncLocalValueMap.Empty, Array.Empty<IAsyncLocal>(), isFlowSuppressed: true);
  25. private readonly IAsyncLocalValueMap m_localValues;
  26. private readonly IAsyncLocal[] m_localChangeNotifications;
  27. private readonly bool m_isFlowSuppressed;
  28. private readonly bool m_isDefault;
  29. private ExecutionContext(bool isDefault)
  30. {
  31. m_isDefault = isDefault;
  32. }
  33. private ExecutionContext(
  34. IAsyncLocalValueMap localValues,
  35. IAsyncLocal[] localChangeNotifications,
  36. bool isFlowSuppressed)
  37. {
  38. m_localValues = localValues;
  39. m_localChangeNotifications = localChangeNotifications;
  40. m_isFlowSuppressed = isFlowSuppressed;
  41. }
  42. public void GetObjectData(SerializationInfo info, StreamingContext context)
  43. {
  44. throw new PlatformNotSupportedException();
  45. }
  46. public static ExecutionContext Capture()
  47. {
  48. ExecutionContext executionContext = Thread.CurrentThread.ExecutionContext;
  49. if (executionContext == null)
  50. {
  51. executionContext = Default;
  52. }
  53. else if (executionContext.m_isFlowSuppressed)
  54. {
  55. executionContext = null;
  56. }
  57. return executionContext;
  58. }
  59. private ExecutionContext ShallowClone(bool isFlowSuppressed)
  60. {
  61. Debug.Assert(isFlowSuppressed != m_isFlowSuppressed);
  62. if (m_localValues == null || AsyncLocalValueMap.IsEmpty(m_localValues))
  63. {
  64. return isFlowSuppressed ?
  65. DefaultFlowSuppressed :
  66. null; // implies the default context
  67. }
  68. return new ExecutionContext(m_localValues, m_localChangeNotifications, isFlowSuppressed);
  69. }
  70. public static AsyncFlowControl SuppressFlow()
  71. {
  72. Thread currentThread = Thread.CurrentThread;
  73. ExecutionContext executionContext = currentThread.ExecutionContext ?? Default;
  74. if (executionContext.m_isFlowSuppressed)
  75. {
  76. throw new InvalidOperationException(SR.InvalidOperation_CannotSupressFlowMultipleTimes);
  77. }
  78. executionContext = executionContext.ShallowClone(isFlowSuppressed: true);
  79. var asyncFlowControl = new AsyncFlowControl();
  80. currentThread.ExecutionContext = executionContext;
  81. asyncFlowControl.Initialize(currentThread);
  82. return asyncFlowControl;
  83. }
  84. public static void RestoreFlow()
  85. {
  86. Thread currentThread = Thread.CurrentThread;
  87. ExecutionContext executionContext = currentThread.ExecutionContext;
  88. if (executionContext == null || !executionContext.m_isFlowSuppressed)
  89. {
  90. throw new InvalidOperationException(SR.InvalidOperation_CannotRestoreUnsupressedFlow);
  91. }
  92. currentThread.ExecutionContext = executionContext.ShallowClone(isFlowSuppressed: false);
  93. }
  94. public static bool IsFlowSuppressed()
  95. {
  96. ExecutionContext executionContext = Thread.CurrentThread.ExecutionContext;
  97. return executionContext != null && executionContext.m_isFlowSuppressed;
  98. }
  99. internal bool HasChangeNotifications => m_localChangeNotifications != null;
  100. internal bool IsDefault => m_isDefault;
  101. public static void Run(ExecutionContext executionContext, ContextCallback callback, object state)
  102. {
  103. // Note: ExecutionContext.Run is an extremely hot function and used by every await, ThreadPool execution, etc.
  104. if (executionContext == null)
  105. {
  106. ThrowNullContext();
  107. }
  108. RunInternal(executionContext, callback, state);
  109. }
  110. internal static void RunInternal(ExecutionContext executionContext, ContextCallback callback, object state)
  111. {
  112. // Note: ExecutionContext.RunInternal is an extremely hot function and used by every await, ThreadPool execution, etc.
  113. // Note: Manual enregistering may be addressed by "Exception Handling Write Through Optimization"
  114. // https://github.com/dotnet/coreclr/blob/master/Documentation/design-docs/eh-writethru.md
  115. // Enregister variables with 0 post-fix so they can be used in registers without EH forcing them to stack
  116. // Capture references to Thread Contexts
  117. Thread currentThread0 = Thread.CurrentThread;
  118. Thread currentThread = currentThread0;
  119. ExecutionContext previousExecutionCtx0 = currentThread0.ExecutionContext;
  120. if (previousExecutionCtx0 != null && previousExecutionCtx0.m_isDefault)
  121. {
  122. // Default is a null ExecutionContext internally
  123. previousExecutionCtx0 = null;
  124. }
  125. // Store current ExecutionContext and SynchronizationContext as "previousXxx".
  126. // This allows us to restore them and undo any Context changes made in callback.Invoke
  127. // so that they won't "leak" back into caller.
  128. // These variables will cross EH so be forced to stack
  129. ExecutionContext previousExecutionCtx = previousExecutionCtx0;
  130. SynchronizationContext previousSyncCtx = currentThread0.SynchronizationContext;
  131. if (executionContext != null && executionContext.m_isDefault)
  132. {
  133. // Default is a null ExecutionContext internally
  134. executionContext = null;
  135. }
  136. if (previousExecutionCtx0 != executionContext)
  137. {
  138. // Restore changed ExecutionContext
  139. currentThread0.ExecutionContext = executionContext;
  140. if ((executionContext != null && executionContext.HasChangeNotifications) ||
  141. (previousExecutionCtx0 != null && previousExecutionCtx0.HasChangeNotifications))
  142. {
  143. // There are change notifications; trigger any affected
  144. OnValuesChanged(previousExecutionCtx0, executionContext);
  145. }
  146. }
  147. ExceptionDispatchInfo edi = null;
  148. try
  149. {
  150. callback.Invoke(state);
  151. }
  152. catch (Exception ex)
  153. {
  154. // Note: we have a "catch" rather than a "finally" because we want
  155. // to stop the first pass of EH here. That way we can restore the previous
  156. // context before any of our callers' EH filters run.
  157. edi = ExceptionDispatchInfo.Capture(ex);
  158. }
  159. // Re-enregistrer variables post EH with 1 post-fix so they can be used in registers rather than from stack
  160. SynchronizationContext previousSyncCtx1 = previousSyncCtx;
  161. Thread currentThread1 = currentThread;
  162. // The common case is that these have not changed, so avoid the cost of a write barrier if not needed.
  163. if (currentThread1.SynchronizationContext != previousSyncCtx1)
  164. {
  165. // Restore changed SynchronizationContext back to previous
  166. currentThread1.SynchronizationContext = previousSyncCtx1;
  167. }
  168. ExecutionContext previousExecutionCtx1 = previousExecutionCtx;
  169. ExecutionContext currentExecutionCtx1 = currentThread1.ExecutionContext;
  170. if (currentExecutionCtx1 != previousExecutionCtx1)
  171. {
  172. // Restore changed ExecutionContext back to previous
  173. currentThread1.ExecutionContext = previousExecutionCtx1;
  174. if ((currentExecutionCtx1 != null && currentExecutionCtx1.HasChangeNotifications) ||
  175. (previousExecutionCtx1 != null && previousExecutionCtx1.HasChangeNotifications))
  176. {
  177. // There are change notifications; trigger any affected
  178. OnValuesChanged(currentExecutionCtx1, previousExecutionCtx1);
  179. }
  180. }
  181. // If exception was thrown by callback, rethrow it now original contexts are restored
  182. edi?.Throw();
  183. }
  184. // Direct copy of the above RunInternal overload, except that it passes the state into the callback strongly-typed and by ref.
  185. internal static void RunInternal<TState>(ExecutionContext executionContext, ContextCallback<TState> callback, ref TState state)
  186. {
  187. // Note: ExecutionContext.RunInternal is an extremely hot function and used by every await, ThreadPool execution, etc.
  188. // Note: Manual enregistering may be addressed by "Exception Handling Write Through Optimization"
  189. // https://github.com/dotnet/coreclr/blob/master/Documentation/design-docs/eh-writethru.md
  190. // Enregister variables with 0 post-fix so they can be used in registers without EH forcing them to stack
  191. // Capture references to Thread Contexts
  192. Thread currentThread0 = Thread.CurrentThread;
  193. Thread currentThread = currentThread0;
  194. ExecutionContext previousExecutionCtx0 = currentThread0.ExecutionContext;
  195. if (previousExecutionCtx0 != null && previousExecutionCtx0.m_isDefault)
  196. {
  197. // Default is a null ExecutionContext internally
  198. previousExecutionCtx0 = null;
  199. }
  200. // Store current ExecutionContext and SynchronizationContext as "previousXxx".
  201. // This allows us to restore them and undo any Context changes made in callback.Invoke
  202. // so that they won't "leak" back into caller.
  203. // These variables will cross EH so be forced to stack
  204. ExecutionContext previousExecutionCtx = previousExecutionCtx0;
  205. SynchronizationContext previousSyncCtx = currentThread0.SynchronizationContext;
  206. if (executionContext != null && executionContext.m_isDefault)
  207. {
  208. // Default is a null ExecutionContext internally
  209. executionContext = null;
  210. }
  211. if (previousExecutionCtx0 != executionContext)
  212. {
  213. // Restore changed ExecutionContext
  214. currentThread0.ExecutionContext = executionContext;
  215. if ((executionContext != null && executionContext.HasChangeNotifications) ||
  216. (previousExecutionCtx0 != null && previousExecutionCtx0.HasChangeNotifications))
  217. {
  218. // There are change notifications; trigger any affected
  219. OnValuesChanged(previousExecutionCtx0, executionContext);
  220. }
  221. }
  222. ExceptionDispatchInfo edi = null;
  223. try
  224. {
  225. callback.Invoke(ref state);
  226. }
  227. catch (Exception ex)
  228. {
  229. // Note: we have a "catch" rather than a "finally" because we want
  230. // to stop the first pass of EH here. That way we can restore the previous
  231. // context before any of our callers' EH filters run.
  232. edi = ExceptionDispatchInfo.Capture(ex);
  233. }
  234. // Re-enregistrer variables post EH with 1 post-fix so they can be used in registers rather than from stack
  235. SynchronizationContext previousSyncCtx1 = previousSyncCtx;
  236. Thread currentThread1 = currentThread;
  237. // The common case is that these have not changed, so avoid the cost of a write barrier if not needed.
  238. if (currentThread1.SynchronizationContext != previousSyncCtx1)
  239. {
  240. // Restore changed SynchronizationContext back to previous
  241. currentThread1.SynchronizationContext = previousSyncCtx1;
  242. }
  243. ExecutionContext previousExecutionCtx1 = previousExecutionCtx;
  244. ExecutionContext currentExecutionCtx1 = currentThread1.ExecutionContext;
  245. if (currentExecutionCtx1 != previousExecutionCtx1)
  246. {
  247. // Restore changed ExecutionContext back to previous
  248. currentThread1.ExecutionContext = previousExecutionCtx1;
  249. if ((currentExecutionCtx1 != null && currentExecutionCtx1.HasChangeNotifications) ||
  250. (previousExecutionCtx1 != null && previousExecutionCtx1.HasChangeNotifications))
  251. {
  252. // There are change notifications; trigger any affected
  253. OnValuesChanged(currentExecutionCtx1, previousExecutionCtx1);
  254. }
  255. }
  256. // If exception was thrown by callback, rethrow it now original contexts are restored
  257. edi?.Throw();
  258. }
  259. internal static void RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, object state)
  260. {
  261. Debug.Assert(threadPoolThread == Thread.CurrentThread);
  262. CheckThreadPoolAndContextsAreDefault();
  263. // ThreadPool starts on Default Context so we don't need to save the "previous" state as we know it is Default (null)
  264. if (executionContext != null && executionContext.m_isDefault)
  265. {
  266. // Default is a null ExecutionContext internally
  267. executionContext = null;
  268. }
  269. else if (executionContext != null)
  270. {
  271. // Non-Default context to restore
  272. threadPoolThread.ExecutionContext = executionContext;
  273. if (executionContext.HasChangeNotifications)
  274. {
  275. // There are change notifications; trigger any affected
  276. OnValuesChanged(previousExecutionCtx: null, executionContext);
  277. }
  278. }
  279. ExceptionDispatchInfo edi = null;
  280. try
  281. {
  282. callback.Invoke(state);
  283. }
  284. catch (Exception ex)
  285. {
  286. // Note: we have a "catch" rather than a "finally" because we want
  287. // to stop the first pass of EH here. That way we can restore the previous
  288. // context before any of our callers' EH filters run.
  289. edi = ExceptionDispatchInfo.Capture(ex);
  290. }
  291. // Enregister threadPoolThread as it crossed EH, and use enregistered variable
  292. Thread currentThread = threadPoolThread;
  293. ExecutionContext currentExecutionCtx = currentThread.ExecutionContext;
  294. // Restore changed SynchronizationContext back to Default
  295. currentThread.SynchronizationContext = null;
  296. if (currentExecutionCtx != null)
  297. {
  298. // The EC always needs to be reset for this overload, as it will flow back to the caller if it performs
  299. // extra work prior to returning to the Dispatch loop. For example for Task-likes it will flow out of await points
  300. // Restore to Default before Notifications, as the change can be observed in the handler.
  301. currentThread.ExecutionContext = null;
  302. if (currentExecutionCtx.HasChangeNotifications)
  303. {
  304. // There are change notifications; trigger any affected
  305. OnValuesChanged(currentExecutionCtx, nextExecutionCtx: null);
  306. }
  307. }
  308. // If exception was thrown by callback, rethrow it now original contexts are restored
  309. edi?.Throw();
  310. }
  311. internal static void RunForThreadPoolUnsafe<TState>(ExecutionContext executionContext, Action<TState> callback, in TState state)
  312. {
  313. // We aren't running in try/catch as if an exception is directly thrown on the ThreadPool either process
  314. // will crash or its a ThreadAbortException.
  315. CheckThreadPoolAndContextsAreDefault();
  316. Debug.Assert(executionContext != null && !executionContext.m_isDefault, "ExecutionContext argument is Default.");
  317. Thread currentThread = Thread.CurrentThread;
  318. // Restore Non-Default context
  319. currentThread.ExecutionContext = executionContext;
  320. if (executionContext.HasChangeNotifications)
  321. {
  322. OnValuesChanged(previousExecutionCtx: null, executionContext);
  323. }
  324. callback.Invoke(state);
  325. // ThreadPoolWorkQueue.Dispatch will handle notifications and reset EC and SyncCtx back to default
  326. }
  327. // Inline as only called in one place and always called
  328. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  329. internal static void ResetThreadPoolThread(Thread currentThread)
  330. {
  331. ExecutionContext currentExecutionCtx = currentThread.ExecutionContext;
  332. // Reset to defaults
  333. currentThread.SynchronizationContext = null;
  334. currentThread.ExecutionContext = null;
  335. if (currentExecutionCtx != null && currentExecutionCtx.HasChangeNotifications)
  336. {
  337. OnValuesChanged(currentExecutionCtx, nextExecutionCtx: null);
  338. // Reset to defaults again without change notifications in case the Change handler changed the contexts
  339. currentThread.SynchronizationContext = null;
  340. currentThread.ExecutionContext = null;
  341. }
  342. }
  343. [System.Diagnostics.Conditional("DEBUG")]
  344. internal static void CheckThreadPoolAndContextsAreDefault()
  345. {
  346. Debug.Assert(Thread.CurrentThread.IsThreadPoolThread);
  347. Debug.Assert(Thread.CurrentThread.ExecutionContext == null, "ThreadPool thread not on Default ExecutionContext.");
  348. Debug.Assert(Thread.CurrentThread.SynchronizationContext == null, "ThreadPool thread not on Default SynchronizationContext.");
  349. }
  350. internal static void OnValuesChanged(ExecutionContext previousExecutionCtx, ExecutionContext nextExecutionCtx)
  351. {
  352. Debug.Assert(previousExecutionCtx != nextExecutionCtx);
  353. // Collect Change Notifications
  354. IAsyncLocal[] previousChangeNotifications = previousExecutionCtx?.m_localChangeNotifications;
  355. IAsyncLocal[] nextChangeNotifications = nextExecutionCtx?.m_localChangeNotifications;
  356. // At least one side must have notifications
  357. Debug.Assert(previousChangeNotifications != null || nextChangeNotifications != null);
  358. // Fire Change Notifications
  359. try
  360. {
  361. if (previousChangeNotifications != null && nextChangeNotifications != null)
  362. {
  363. // Notifications can't exist without values
  364. Debug.Assert(previousExecutionCtx.m_localValues != null);
  365. Debug.Assert(nextExecutionCtx.m_localValues != null);
  366. // Both contexts have change notifications, check previousExecutionCtx first
  367. foreach (IAsyncLocal local in previousChangeNotifications)
  368. {
  369. previousExecutionCtx.m_localValues.TryGetValue(local, out object previousValue);
  370. nextExecutionCtx.m_localValues.TryGetValue(local, out object currentValue);
  371. if (previousValue != currentValue)
  372. {
  373. local.OnValueChanged(previousValue, currentValue, contextChanged: true);
  374. }
  375. }
  376. if (nextChangeNotifications != previousChangeNotifications)
  377. {
  378. // Check for additional notifications in nextExecutionCtx
  379. foreach (IAsyncLocal local in nextChangeNotifications)
  380. {
  381. // If the local has a value in the previous context, we already fired the event
  382. // for that local in the code above.
  383. if (!previousExecutionCtx.m_localValues.TryGetValue(local, out object previousValue))
  384. {
  385. nextExecutionCtx.m_localValues.TryGetValue(local, out object currentValue);
  386. if (previousValue != currentValue)
  387. {
  388. local.OnValueChanged(previousValue, currentValue, contextChanged: true);
  389. }
  390. }
  391. }
  392. }
  393. }
  394. else if (previousChangeNotifications != null)
  395. {
  396. // Notifications can't exist without values
  397. Debug.Assert(previousExecutionCtx.m_localValues != null);
  398. // No current values, so just check previous against null
  399. foreach (IAsyncLocal local in previousChangeNotifications)
  400. {
  401. previousExecutionCtx.m_localValues.TryGetValue(local, out object previousValue);
  402. if (previousValue != null)
  403. {
  404. local.OnValueChanged(previousValue, null, contextChanged: true);
  405. }
  406. }
  407. }
  408. else // Implied: nextChangeNotifications != null
  409. {
  410. // Notifications can't exist without values
  411. Debug.Assert(nextExecutionCtx.m_localValues != null);
  412. // No previous values, so just check current against null
  413. foreach (IAsyncLocal local in nextChangeNotifications)
  414. {
  415. nextExecutionCtx.m_localValues.TryGetValue(local, out object currentValue);
  416. if (currentValue != null)
  417. {
  418. local.OnValueChanged(null, currentValue, contextChanged: true);
  419. }
  420. }
  421. }
  422. }
  423. catch (Exception ex)
  424. {
  425. Environment.FailFast(
  426. SR.ExecutionContext_ExceptionInAsyncLocalNotification,
  427. ex);
  428. }
  429. }
  430. [StackTraceHidden]
  431. private static void ThrowNullContext()
  432. {
  433. throw new InvalidOperationException(SR.InvalidOperation_NullContext);
  434. }
  435. internal static object GetLocalValue(IAsyncLocal local)
  436. {
  437. ExecutionContext current = Thread.CurrentThread.ExecutionContext;
  438. if (current == null)
  439. {
  440. return null;
  441. }
  442. current.m_localValues.TryGetValue(local, out object value);
  443. return value;
  444. }
  445. internal static void SetLocalValue(IAsyncLocal local, object newValue, bool needChangeNotifications)
  446. {
  447. ExecutionContext current = Thread.CurrentThread.ExecutionContext;
  448. object previousValue = null;
  449. bool hadPreviousValue = false;
  450. if (current != null)
  451. {
  452. hadPreviousValue = current.m_localValues.TryGetValue(local, out previousValue);
  453. }
  454. if (previousValue == newValue)
  455. {
  456. return;
  457. }
  458. // Regarding 'treatNullValueAsNonexistent: !needChangeNotifications' below:
  459. // - When change notifications are not necessary for this IAsyncLocal, there is no observable difference between
  460. // storing a null value and removing the IAsyncLocal from 'm_localValues'
  461. // - When change notifications are necessary for this IAsyncLocal, the IAsyncLocal's absence in 'm_localValues'
  462. // indicates that this is the first value change for the IAsyncLocal and it needs to be registered for change
  463. // notifications. So in this case, a null value must be stored in 'm_localValues' to indicate that the IAsyncLocal
  464. // is already registered for change notifications.
  465. IAsyncLocal[] newChangeNotifications = null;
  466. IAsyncLocalValueMap newValues;
  467. bool isFlowSuppressed = false;
  468. if (current != null)
  469. {
  470. isFlowSuppressed = current.m_isFlowSuppressed;
  471. newValues = current.m_localValues.Set(local, newValue, treatNullValueAsNonexistent: !needChangeNotifications);
  472. newChangeNotifications = current.m_localChangeNotifications;
  473. }
  474. else
  475. {
  476. // First AsyncLocal
  477. newValues = AsyncLocalValueMap.Create(local, newValue, treatNullValueAsNonexistent: !needChangeNotifications);
  478. }
  479. //
  480. // Either copy the change notification array, or create a new one, depending on whether we need to add a new item.
  481. //
  482. if (needChangeNotifications)
  483. {
  484. if (hadPreviousValue)
  485. {
  486. Debug.Assert(newChangeNotifications != null);
  487. Debug.Assert(Array.IndexOf(newChangeNotifications, local) >= 0);
  488. }
  489. else if (newChangeNotifications == null)
  490. {
  491. newChangeNotifications = new IAsyncLocal[1] { local };
  492. }
  493. else
  494. {
  495. int newNotificationIndex = newChangeNotifications.Length;
  496. Array.Resize(ref newChangeNotifications, newNotificationIndex + 1);
  497. newChangeNotifications[newNotificationIndex] = local;
  498. }
  499. }
  500. Thread.CurrentThread.ExecutionContext =
  501. (!isFlowSuppressed && AsyncLocalValueMap.IsEmpty(newValues)) ?
  502. null : // No values, return to Default context
  503. new ExecutionContext(newValues, newChangeNotifications, isFlowSuppressed);
  504. if (needChangeNotifications)
  505. {
  506. local.OnValueChanged(previousValue, newValue, contextChanged: false);
  507. }
  508. }
  509. public ExecutionContext CreateCopy()
  510. {
  511. return this; // since CoreCLR's ExecutionContext is immutable, we don't need to create copies.
  512. }
  513. public void Dispose()
  514. {
  515. // For CLR compat only
  516. }
  517. }
  518. public struct AsyncFlowControl : IDisposable
  519. {
  520. private Thread _thread;
  521. internal void Initialize(Thread currentThread)
  522. {
  523. Debug.Assert(currentThread == Thread.CurrentThread);
  524. _thread = currentThread;
  525. }
  526. public void Undo()
  527. {
  528. if (_thread == null)
  529. {
  530. throw new InvalidOperationException(SR.InvalidOperation_CannotUseAFCMultiple);
  531. }
  532. if (Thread.CurrentThread != _thread)
  533. {
  534. throw new InvalidOperationException(SR.InvalidOperation_CannotUseAFCOtherThread);
  535. }
  536. // An async flow control cannot be undone when a different execution context is applied. The desktop framework
  537. // mutates the execution context when its state changes, and only changes the instance when an execution context
  538. // is applied (for instance, through ExecutionContext.Run). The framework prevents a suppressed-flow execution
  539. // context from being applied by returning null from ExecutionContext.Capture, so the only type of execution
  540. // context that can be applied is one whose flow is not suppressed. After suppressing flow and changing an async
  541. // local's value, the desktop framework verifies that a different execution context has not been applied by
  542. // checking the execution context instance against the one saved from when flow was suppressed. In .NET Core,
  543. // since the execution context instance will change after changing the async local's value, it verifies that a
  544. // different execution context has not been applied, by instead ensuring that the current execution context's
  545. // flow is suppressed.
  546. if (!ExecutionContext.IsFlowSuppressed())
  547. {
  548. throw new InvalidOperationException(SR.InvalidOperation_AsyncFlowCtrlCtxMismatch);
  549. }
  550. _thread = null;
  551. ExecutionContext.RestoreFlow();
  552. }
  553. public void Dispose()
  554. {
  555. Undo();
  556. }
  557. public override bool Equals(object obj)
  558. {
  559. return obj is AsyncFlowControl && Equals((AsyncFlowControl)obj);
  560. }
  561. public bool Equals(AsyncFlowControl obj)
  562. {
  563. return _thread == obj._thread;
  564. }
  565. public override int GetHashCode()
  566. {
  567. return _thread?.GetHashCode() ?? 0;
  568. }
  569. public static bool operator ==(AsyncFlowControl a, AsyncFlowControl b)
  570. {
  571. return a.Equals(b);
  572. }
  573. public static bool operator !=(AsyncFlowControl a, AsyncFlowControl b)
  574. {
  575. return !(a == b);
  576. }
  577. }
  578. }