ExecutionContext.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  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. RestoreChangedContextToThread(currentThread0, executionContext, previousExecutionCtx0);
  139. }
  140. ExceptionDispatchInfo edi = null;
  141. try
  142. {
  143. callback.Invoke(state);
  144. }
  145. catch (Exception ex)
  146. {
  147. // Note: we have a "catch" rather than a "finally" because we want
  148. // to stop the first pass of EH here. That way we can restore the previous
  149. // context before any of our callers' EH filters run.
  150. edi = ExceptionDispatchInfo.Capture(ex);
  151. }
  152. // Re-enregistrer variables post EH with 1 post-fix so they can be used in registers rather than from stack
  153. SynchronizationContext previousSyncCtx1 = previousSyncCtx;
  154. Thread currentThread1 = currentThread;
  155. // The common case is that these have not changed, so avoid the cost of a write barrier if not needed.
  156. if (currentThread1.SynchronizationContext != previousSyncCtx1)
  157. {
  158. // Restore changed SynchronizationContext back to previous
  159. currentThread1.SynchronizationContext = previousSyncCtx1;
  160. }
  161. ExecutionContext previousExecutionCtx1 = previousExecutionCtx;
  162. ExecutionContext currentExecutionCtx1 = currentThread1.ExecutionContext;
  163. if (currentExecutionCtx1 != previousExecutionCtx1)
  164. {
  165. RestoreChangedContextToThread(currentThread1, previousExecutionCtx1, currentExecutionCtx1);
  166. }
  167. // If exception was thrown by callback, rethrow it now original contexts are restored
  168. edi?.Throw();
  169. }
  170. // Direct copy of the above RunInternal overload, except that it passes the state into the callback strongly-typed and by ref.
  171. internal static void RunInternal<TState>(ExecutionContext executionContext, ContextCallback<TState> callback, ref TState state)
  172. {
  173. // Note: ExecutionContext.RunInternal is an extremely hot function and used by every await, ThreadPool execution, etc.
  174. // Note: Manual enregistering may be addressed by "Exception Handling Write Through Optimization"
  175. // https://github.com/dotnet/coreclr/blob/master/Documentation/design-docs/eh-writethru.md
  176. // Enregister variables with 0 post-fix so they can be used in registers without EH forcing them to stack
  177. // Capture references to Thread Contexts
  178. Thread currentThread0 = Thread.CurrentThread;
  179. Thread currentThread = currentThread0;
  180. ExecutionContext previousExecutionCtx0 = currentThread0.ExecutionContext;
  181. if (previousExecutionCtx0 != null && previousExecutionCtx0.m_isDefault)
  182. {
  183. // Default is a null ExecutionContext internally
  184. previousExecutionCtx0 = null;
  185. }
  186. // Store current ExecutionContext and SynchronizationContext as "previousXxx".
  187. // This allows us to restore them and undo any Context changes made in callback.Invoke
  188. // so that they won't "leak" back into caller.
  189. // These variables will cross EH so be forced to stack
  190. ExecutionContext previousExecutionCtx = previousExecutionCtx0;
  191. SynchronizationContext previousSyncCtx = currentThread0.SynchronizationContext;
  192. if (executionContext != null && executionContext.m_isDefault)
  193. {
  194. // Default is a null ExecutionContext internally
  195. executionContext = null;
  196. }
  197. if (previousExecutionCtx0 != executionContext)
  198. {
  199. RestoreChangedContextToThread(currentThread0, executionContext, previousExecutionCtx0);
  200. }
  201. ExceptionDispatchInfo edi = null;
  202. try
  203. {
  204. callback.Invoke(ref state);
  205. }
  206. catch (Exception ex)
  207. {
  208. // Note: we have a "catch" rather than a "finally" because we want
  209. // to stop the first pass of EH here. That way we can restore the previous
  210. // context before any of our callers' EH filters run.
  211. edi = ExceptionDispatchInfo.Capture(ex);
  212. }
  213. // Re-enregistrer variables post EH with 1 post-fix so they can be used in registers rather than from stack
  214. SynchronizationContext previousSyncCtx1 = previousSyncCtx;
  215. Thread currentThread1 = currentThread;
  216. // The common case is that these have not changed, so avoid the cost of a write barrier if not needed.
  217. if (currentThread1.SynchronizationContext != previousSyncCtx1)
  218. {
  219. // Restore changed SynchronizationContext back to previous
  220. currentThread1.SynchronizationContext = previousSyncCtx1;
  221. }
  222. ExecutionContext previousExecutionCtx1 = previousExecutionCtx;
  223. ExecutionContext currentExecutionCtx1 = currentThread1.ExecutionContext;
  224. if (currentExecutionCtx1 != previousExecutionCtx1)
  225. {
  226. RestoreChangedContextToThread(currentThread1, previousExecutionCtx1, currentExecutionCtx1);
  227. }
  228. // If exception was thrown by callback, rethrow it now original contexts are restored
  229. edi?.Throw();
  230. }
  231. internal static void RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, object state)
  232. {
  233. Debug.Assert(threadPoolThread == Thread.CurrentThread);
  234. CheckThreadPoolAndContextsAreDefault();
  235. // ThreadPool starts on Default Context so we don't need to save the "previous" state as we know it is Default (null)
  236. // Default is a null ExecutionContext internally
  237. if (executionContext != null && !executionContext.m_isDefault)
  238. {
  239. // Non-Default context to restore
  240. RestoreChangedContextToThread(threadPoolThread, contextToRestore: executionContext, currentContext: null);
  241. }
  242. ExceptionDispatchInfo edi = null;
  243. try
  244. {
  245. callback.Invoke(state);
  246. }
  247. catch (Exception ex)
  248. {
  249. // Note: we have a "catch" rather than a "finally" because we want
  250. // to stop the first pass of EH here. That way we can restore the previous
  251. // context before any of our callers' EH filters run.
  252. edi = ExceptionDispatchInfo.Capture(ex);
  253. }
  254. // Enregister threadPoolThread as it crossed EH, and use enregistered variable
  255. Thread currentThread = threadPoolThread;
  256. ExecutionContext currentExecutionCtx = currentThread.ExecutionContext;
  257. // Restore changed SynchronizationContext back to Default
  258. currentThread.SynchronizationContext = null;
  259. if (currentExecutionCtx != null)
  260. {
  261. // The EC always needs to be reset for this overload, as it will flow back to the caller if it performs
  262. // extra work prior to returning to the Dispatch loop. For example for Task-likes it will flow out of await points
  263. RestoreChangedContextToThread(currentThread, contextToRestore: null, currentExecutionCtx);
  264. }
  265. // If exception was thrown by callback, rethrow it now original contexts are restored
  266. edi?.Throw();
  267. }
  268. internal static void RunForThreadPoolUnsafe<TState>(ExecutionContext executionContext, Action<TState> callback, in TState state)
  269. {
  270. // We aren't running in try/catch as if an exception is directly thrown on the ThreadPool either process
  271. // will crash or its a ThreadAbortException.
  272. CheckThreadPoolAndContextsAreDefault();
  273. Debug.Assert(executionContext != null && !executionContext.m_isDefault, "ExecutionContext argument is Default.");
  274. // Restore Non-Default context
  275. Thread.CurrentThread.ExecutionContext = executionContext;
  276. if (executionContext.HasChangeNotifications)
  277. {
  278. OnValuesChanged(previousExecutionCtx: null, executionContext);
  279. }
  280. callback.Invoke(state);
  281. // ThreadPoolWorkQueue.Dispatch will handle notifications and reset EC and SyncCtx back to default
  282. }
  283. internal static void RestoreChangedContextToThread(Thread currentThread, ExecutionContext contextToRestore, ExecutionContext currentContext)
  284. {
  285. Debug.Assert(currentThread == Thread.CurrentThread);
  286. Debug.Assert(contextToRestore != currentContext);
  287. // Restore changed ExecutionContext back to previous
  288. currentThread.ExecutionContext = contextToRestore;
  289. if ((currentContext != null && currentContext.HasChangeNotifications) ||
  290. (contextToRestore != null && contextToRestore.HasChangeNotifications))
  291. {
  292. // There are change notifications; trigger any affected
  293. OnValuesChanged(currentContext, contextToRestore);
  294. }
  295. }
  296. // Inline as only called in one place and always called
  297. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  298. internal static void ResetThreadPoolThread(Thread currentThread)
  299. {
  300. ExecutionContext currentExecutionCtx = currentThread.ExecutionContext;
  301. // Reset to defaults
  302. currentThread.SynchronizationContext = null;
  303. currentThread.ExecutionContext = null;
  304. if (currentExecutionCtx != null && currentExecutionCtx.HasChangeNotifications)
  305. {
  306. OnValuesChanged(currentExecutionCtx, nextExecutionCtx: null);
  307. // Reset to defaults again without change notifications in case the Change handler changed the contexts
  308. currentThread.SynchronizationContext = null;
  309. currentThread.ExecutionContext = null;
  310. }
  311. }
  312. [System.Diagnostics.Conditional("DEBUG")]
  313. internal static void CheckThreadPoolAndContextsAreDefault()
  314. {
  315. Debug.Assert(Thread.CurrentThread.IsThreadPoolThread);
  316. Debug.Assert(Thread.CurrentThread.ExecutionContext == null, "ThreadPool thread not on Default ExecutionContext.");
  317. Debug.Assert(Thread.CurrentThread.SynchronizationContext == null, "ThreadPool thread not on Default SynchronizationContext.");
  318. }
  319. internal static void OnValuesChanged(ExecutionContext previousExecutionCtx, ExecutionContext nextExecutionCtx)
  320. {
  321. Debug.Assert(previousExecutionCtx != nextExecutionCtx);
  322. // Collect Change Notifications
  323. IAsyncLocal[] previousChangeNotifications = previousExecutionCtx?.m_localChangeNotifications;
  324. IAsyncLocal[] nextChangeNotifications = nextExecutionCtx?.m_localChangeNotifications;
  325. // At least one side must have notifications
  326. Debug.Assert(previousChangeNotifications != null || nextChangeNotifications != null);
  327. // Fire Change Notifications
  328. try
  329. {
  330. if (previousChangeNotifications != null && nextChangeNotifications != null)
  331. {
  332. // Notifications can't exist without values
  333. Debug.Assert(previousExecutionCtx.m_localValues != null);
  334. Debug.Assert(nextExecutionCtx.m_localValues != null);
  335. // Both contexts have change notifications, check previousExecutionCtx first
  336. foreach (IAsyncLocal local in previousChangeNotifications)
  337. {
  338. previousExecutionCtx.m_localValues.TryGetValue(local, out object previousValue);
  339. nextExecutionCtx.m_localValues.TryGetValue(local, out object currentValue);
  340. if (previousValue != currentValue)
  341. {
  342. local.OnValueChanged(previousValue, currentValue, contextChanged: true);
  343. }
  344. }
  345. if (nextChangeNotifications != previousChangeNotifications)
  346. {
  347. // Check for additional notifications in nextExecutionCtx
  348. foreach (IAsyncLocal local in nextChangeNotifications)
  349. {
  350. // If the local has a value in the previous context, we already fired the event
  351. // for that local in the code above.
  352. if (!previousExecutionCtx.m_localValues.TryGetValue(local, out object previousValue))
  353. {
  354. nextExecutionCtx.m_localValues.TryGetValue(local, out object currentValue);
  355. if (previousValue != currentValue)
  356. {
  357. local.OnValueChanged(previousValue, currentValue, contextChanged: true);
  358. }
  359. }
  360. }
  361. }
  362. }
  363. else if (previousChangeNotifications != null)
  364. {
  365. // Notifications can't exist without values
  366. Debug.Assert(previousExecutionCtx.m_localValues != null);
  367. // No current values, so just check previous against null
  368. foreach (IAsyncLocal local in previousChangeNotifications)
  369. {
  370. previousExecutionCtx.m_localValues.TryGetValue(local, out object previousValue);
  371. if (previousValue != null)
  372. {
  373. local.OnValueChanged(previousValue, null, contextChanged: true);
  374. }
  375. }
  376. }
  377. else // Implied: nextChangeNotifications != null
  378. {
  379. // Notifications can't exist without values
  380. Debug.Assert(nextExecutionCtx.m_localValues != null);
  381. // No previous values, so just check current against null
  382. foreach (IAsyncLocal local in nextChangeNotifications)
  383. {
  384. nextExecutionCtx.m_localValues.TryGetValue(local, out object currentValue);
  385. if (currentValue != null)
  386. {
  387. local.OnValueChanged(null, currentValue, contextChanged: true);
  388. }
  389. }
  390. }
  391. }
  392. catch (Exception ex)
  393. {
  394. Environment.FailFast(
  395. SR.ExecutionContext_ExceptionInAsyncLocalNotification,
  396. ex);
  397. }
  398. }
  399. [StackTraceHidden]
  400. private static void ThrowNullContext()
  401. {
  402. throw new InvalidOperationException(SR.InvalidOperation_NullContext);
  403. }
  404. internal static object GetLocalValue(IAsyncLocal local)
  405. {
  406. ExecutionContext current = Thread.CurrentThread.ExecutionContext;
  407. if (current == null)
  408. {
  409. return null;
  410. }
  411. current.m_localValues.TryGetValue(local, out object value);
  412. return value;
  413. }
  414. internal static void SetLocalValue(IAsyncLocal local, object newValue, bool needChangeNotifications)
  415. {
  416. ExecutionContext current = Thread.CurrentThread.ExecutionContext;
  417. object previousValue = null;
  418. bool hadPreviousValue = false;
  419. if (current != null)
  420. {
  421. hadPreviousValue = current.m_localValues.TryGetValue(local, out previousValue);
  422. }
  423. if (previousValue == newValue)
  424. {
  425. return;
  426. }
  427. // Regarding 'treatNullValueAsNonexistent: !needChangeNotifications' below:
  428. // - When change notifications are not necessary for this IAsyncLocal, there is no observable difference between
  429. // storing a null value and removing the IAsyncLocal from 'm_localValues'
  430. // - When change notifications are necessary for this IAsyncLocal, the IAsyncLocal's absence in 'm_localValues'
  431. // indicates that this is the first value change for the IAsyncLocal and it needs to be registered for change
  432. // notifications. So in this case, a null value must be stored in 'm_localValues' to indicate that the IAsyncLocal
  433. // is already registered for change notifications.
  434. IAsyncLocal[] newChangeNotifications = null;
  435. IAsyncLocalValueMap newValues;
  436. bool isFlowSuppressed = false;
  437. if (current != null)
  438. {
  439. isFlowSuppressed = current.m_isFlowSuppressed;
  440. newValues = current.m_localValues.Set(local, newValue, treatNullValueAsNonexistent: !needChangeNotifications);
  441. newChangeNotifications = current.m_localChangeNotifications;
  442. }
  443. else
  444. {
  445. // First AsyncLocal
  446. newValues = AsyncLocalValueMap.Create(local, newValue, treatNullValueAsNonexistent: !needChangeNotifications);
  447. }
  448. //
  449. // Either copy the change notification array, or create a new one, depending on whether we need to add a new item.
  450. //
  451. if (needChangeNotifications)
  452. {
  453. if (hadPreviousValue)
  454. {
  455. Debug.Assert(newChangeNotifications != null);
  456. Debug.Assert(Array.IndexOf(newChangeNotifications, local) >= 0);
  457. }
  458. else if (newChangeNotifications == null)
  459. {
  460. newChangeNotifications = new IAsyncLocal[1] { local };
  461. }
  462. else
  463. {
  464. int newNotificationIndex = newChangeNotifications.Length;
  465. Array.Resize(ref newChangeNotifications, newNotificationIndex + 1);
  466. newChangeNotifications[newNotificationIndex] = local;
  467. }
  468. }
  469. Thread.CurrentThread.ExecutionContext =
  470. (!isFlowSuppressed && AsyncLocalValueMap.IsEmpty(newValues)) ?
  471. null : // No values, return to Default context
  472. new ExecutionContext(newValues, newChangeNotifications, isFlowSuppressed);
  473. if (needChangeNotifications)
  474. {
  475. local.OnValueChanged(previousValue, newValue, contextChanged: false);
  476. }
  477. }
  478. public ExecutionContext CreateCopy()
  479. {
  480. return this; // since CoreCLR's ExecutionContext is immutable, we don't need to create copies.
  481. }
  482. public void Dispose()
  483. {
  484. // For CLR compat only
  485. }
  486. }
  487. public struct AsyncFlowControl : IDisposable
  488. {
  489. private Thread _thread;
  490. internal void Initialize(Thread currentThread)
  491. {
  492. Debug.Assert(currentThread == Thread.CurrentThread);
  493. _thread = currentThread;
  494. }
  495. public void Undo()
  496. {
  497. if (_thread == null)
  498. {
  499. throw new InvalidOperationException(SR.InvalidOperation_CannotUseAFCMultiple);
  500. }
  501. if (Thread.CurrentThread != _thread)
  502. {
  503. throw new InvalidOperationException(SR.InvalidOperation_CannotUseAFCOtherThread);
  504. }
  505. // An async flow control cannot be undone when a different execution context is applied. The desktop framework
  506. // mutates the execution context when its state changes, and only changes the instance when an execution context
  507. // is applied (for instance, through ExecutionContext.Run). The framework prevents a suppressed-flow execution
  508. // context from being applied by returning null from ExecutionContext.Capture, so the only type of execution
  509. // context that can be applied is one whose flow is not suppressed. After suppressing flow and changing an async
  510. // local's value, the desktop framework verifies that a different execution context has not been applied by
  511. // checking the execution context instance against the one saved from when flow was suppressed. In .NET Core,
  512. // since the execution context instance will change after changing the async local's value, it verifies that a
  513. // different execution context has not been applied, by instead ensuring that the current execution context's
  514. // flow is suppressed.
  515. if (!ExecutionContext.IsFlowSuppressed())
  516. {
  517. throw new InvalidOperationException(SR.InvalidOperation_AsyncFlowCtrlCtxMismatch);
  518. }
  519. _thread = null;
  520. ExecutionContext.RestoreFlow();
  521. }
  522. public void Dispose()
  523. {
  524. Undo();
  525. }
  526. public override bool Equals(object obj)
  527. {
  528. return obj is AsyncFlowControl && Equals((AsyncFlowControl)obj);
  529. }
  530. public bool Equals(AsyncFlowControl obj)
  531. {
  532. return _thread == obj._thread;
  533. }
  534. public override int GetHashCode()
  535. {
  536. return _thread?.GetHashCode() ?? 0;
  537. }
  538. public static bool operator ==(AsyncFlowControl a, AsyncFlowControl b)
  539. {
  540. return a.Equals(b);
  541. }
  542. public static bool operator !=(AsyncFlowControl a, AsyncFlowControl b)
  543. {
  544. return !(a == b);
  545. }
  546. }
  547. }