public static async Task DoIsolatedAsync(Func <Task> callback) { var previousState = SandboxedThreadState.Capture(); try { var executionContext = ExecutionContext.Capture() ?? throw new InvalidOperationException("Execution context flow must not be suppressed."); using ((object)executionContext as IDisposable) { var context = SynchronizationContext.Current; if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA && (context == null || context.GetType() == typeof(SynchronizationContext))) { ExecutionContext.Run(executionContext, _ => callback().GetAwaiter().GetResult(), null); } else { using (var sc = new FlowingSynchronizationContext(executionContext)) await sc.Run(callback); } } } finally { previousState.Restore(); } }
public static void DoIsolated(ContextCallback callback, object state) { var previousState = SandboxedThreadState.Capture(); try { var executionContext = ExecutionContext.Capture() ?? throw new InvalidOperationException("Execution context flow must not be suppressed."); using ((object)executionContext as IDisposable) { ExecutionContext.Run(executionContext, callback, state); } } finally { previousState.Restore(); } }
/// <summary> /// Record any changes in the environment made by /// the test code in the execution context so it /// will be passed on to lower level tests. /// </summary> public void UpdateContextFromEnvironment() { _sandboxedThreadState = SandboxedThreadState.Capture(); }