ExecutionContext.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  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.Diagnostics.CodeAnalysis;
  14. using System.Runtime.CompilerServices;
  15. using System.Runtime.ExceptionServices;
  16. using System.Runtime.Serialization;
  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. [DoesNotReturn]
  400. [StackTraceHidden]
  401. private static void ThrowNullContext()
  402. {
  403. throw new InvalidOperationException(SR.InvalidOperation_NullContext);
  404. }
  405. internal static object? GetLocalValue(IAsyncLocal local)
  406. {
  407. ExecutionContext? current = Thread.CurrentThread._executionContext;
  408. if (current == null)
  409. {
  410. return null;
  411. }
  412. Debug.Assert(!current.IsDefault);
  413. Debug.Assert(current.m_localValues != null, "Only the default context should have null, and we shouldn't be here on the default context");
  414. current.m_localValues.TryGetValue(local, out object? value);
  415. return value;
  416. }
  417. internal static void SetLocalValue(IAsyncLocal local, object? newValue, bool needChangeNotifications)
  418. {
  419. ExecutionContext? current = Thread.CurrentThread._executionContext;
  420. object? previousValue = null;
  421. bool hadPreviousValue = false;
  422. if (current != null)
  423. {
  424. Debug.Assert(!current.IsDefault);
  425. Debug.Assert(current.m_localValues != null, "Only the default context should have null, and we shouldn't be here on the default context");
  426. hadPreviousValue = current.m_localValues.TryGetValue(local, out previousValue);
  427. }
  428. if (previousValue == newValue)
  429. {
  430. return;
  431. }
  432. // Regarding 'treatNullValueAsNonexistent: !needChangeNotifications' below:
  433. // - When change notifications are not necessary for this IAsyncLocal, there is no observable difference between
  434. // storing a null value and removing the IAsyncLocal from 'm_localValues'
  435. // - When change notifications are necessary for this IAsyncLocal, the IAsyncLocal's absence in 'm_localValues'
  436. // indicates that this is the first value change for the IAsyncLocal and it needs to be registered for change
  437. // notifications. So in this case, a null value must be stored in 'm_localValues' to indicate that the IAsyncLocal
  438. // is already registered for change notifications.
  439. IAsyncLocal[]? newChangeNotifications = null;
  440. IAsyncLocalValueMap newValues;
  441. bool isFlowSuppressed = false;
  442. if (current != null)
  443. {
  444. Debug.Assert(!current.IsDefault);
  445. Debug.Assert(current.m_localValues != null, "Only the default context should have null, and we shouldn't be here on the default context");
  446. isFlowSuppressed = current.m_isFlowSuppressed;
  447. newValues = current.m_localValues.Set(local, newValue, treatNullValueAsNonexistent: !needChangeNotifications);
  448. newChangeNotifications = current.m_localChangeNotifications;
  449. }
  450. else
  451. {
  452. // First AsyncLocal
  453. newValues = AsyncLocalValueMap.Create(local, newValue, treatNullValueAsNonexistent: !needChangeNotifications);
  454. }
  455. //
  456. // Either copy the change notification array, or create a new one, depending on whether we need to add a new item.
  457. //
  458. if (needChangeNotifications)
  459. {
  460. if (hadPreviousValue)
  461. {
  462. Debug.Assert(newChangeNotifications != null);
  463. Debug.Assert(Array.IndexOf(newChangeNotifications, local) >= 0);
  464. }
  465. else if (newChangeNotifications == null)
  466. {
  467. newChangeNotifications = new IAsyncLocal[1] { local };
  468. }
  469. else
  470. {
  471. int newNotificationIndex = newChangeNotifications.Length;
  472. Array.Resize(ref newChangeNotifications, newNotificationIndex + 1);
  473. newChangeNotifications[newNotificationIndex] = local;
  474. }
  475. }
  476. Thread.CurrentThread._executionContext =
  477. (!isFlowSuppressed && AsyncLocalValueMap.IsEmpty(newValues)) ?
  478. null : // No values, return to Default context
  479. new ExecutionContext(newValues, newChangeNotifications, isFlowSuppressed);
  480. if (needChangeNotifications)
  481. {
  482. local.OnValueChanged(previousValue, newValue, contextChanged: false);
  483. }
  484. }
  485. public ExecutionContext CreateCopy()
  486. {
  487. return this; // since CoreCLR's ExecutionContext is immutable, we don't need to create copies.
  488. }
  489. public void Dispose()
  490. {
  491. // For CLR compat only
  492. }
  493. }
  494. public struct AsyncFlowControl : IDisposable
  495. {
  496. private Thread? _thread;
  497. internal void Initialize(Thread currentThread)
  498. {
  499. Debug.Assert(currentThread == Thread.CurrentThread);
  500. _thread = currentThread;
  501. }
  502. public void Undo()
  503. {
  504. if (_thread == null)
  505. {
  506. throw new InvalidOperationException(SR.InvalidOperation_CannotUseAFCMultiple);
  507. }
  508. if (Thread.CurrentThread != _thread)
  509. {
  510. throw new InvalidOperationException(SR.InvalidOperation_CannotUseAFCOtherThread);
  511. }
  512. // An async flow control cannot be undone when a different execution context is applied. The desktop framework
  513. // mutates the execution context when its state changes, and only changes the instance when an execution context
  514. // is applied (for instance, through ExecutionContext.Run). The framework prevents a suppressed-flow execution
  515. // context from being applied by returning null from ExecutionContext.Capture, so the only type of execution
  516. // context that can be applied is one whose flow is not suppressed. After suppressing flow and changing an async
  517. // local's value, the desktop framework verifies that a different execution context has not been applied by
  518. // checking the execution context instance against the one saved from when flow was suppressed. In .NET Core,
  519. // since the execution context instance will change after changing the async local's value, it verifies that a
  520. // different execution context has not been applied, by instead ensuring that the current execution context's
  521. // flow is suppressed.
  522. if (!ExecutionContext.IsFlowSuppressed())
  523. {
  524. throw new InvalidOperationException(SR.InvalidOperation_AsyncFlowCtrlCtxMismatch);
  525. }
  526. _thread = null;
  527. ExecutionContext.RestoreFlow();
  528. }
  529. public void Dispose()
  530. {
  531. Undo();
  532. }
  533. public override bool Equals(object? obj)
  534. {
  535. return obj is AsyncFlowControl && Equals((AsyncFlowControl)obj);
  536. }
  537. public bool Equals(AsyncFlowControl obj)
  538. {
  539. return _thread == obj._thread;
  540. }
  541. public override int GetHashCode()
  542. {
  543. return _thread?.GetHashCode() ?? 0;
  544. }
  545. public static bool operator ==(AsyncFlowControl a, AsyncFlowControl b)
  546. {
  547. return a.Equals(b);
  548. }
  549. public static bool operator !=(AsyncFlowControl a, AsyncFlowControl b)
  550. {
  551. return !(a == b);
  552. }
  553. }
  554. }