ExecutionContext.cs 29 KB

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