public static IDisposable Change(AmbientStuff stuff) { var oldValue = Current; Current = stuff; return(new DisposeAction(() => { Current = oldValue; })); }
private async Task DoStuff(int id) { using (AmbientStuff.Change(new AmbientStuff(AmbientStuff.Current.Value, AmbientStuff.Current.Stack.Push("DoStuff")))) { await Task.Run(async() => { WriteToConsole($"Task {id} - before await"); await Task.Delay(1000); WriteToConsole($"Task {id} - after await"); }); } }
private async Task DoStuff2(int id, int newValue) { using (AmbientStuff.Change(new AmbientStuff(AmbientStuff.Current.Value, AmbientStuff.Current.Stack.Push("DoStuff2")))) { await Task.Run(async() => { WriteToConsole($"Task {id} - before using"); using (AmbientStuff.Change(new AmbientStuff(newValue, AmbientStuff.Current.Stack))) { WriteToConsole($"Task {id} - inside using, before await"); await DoStuff(id); WriteToConsole($"Task {id} - inside using, after await"); } WriteToConsole($"Task {id} - after using"); }); } }
private async Task DoThings(int ambientValue, int taskValue) { using (AmbientStuff.Change(new AmbientStuff(AmbientStuff.Current.Value, AmbientStuff.Current.Stack.Push("DoThings")))) { await Task.Run(async() => { WriteToConsole($"Task {taskValue} - before using"); using (AmbientStuff.Change(new AmbientStuff(ambientValue, AmbientStuff.Current.Stack))) { WriteToConsole($"Task {taskValue} - inside using, before await DoStuff2"); await DoStuff2(taskValue, ambientValue * 3); WriteToConsole($"Task {taskValue} - inside using, after await DoStuff2"); } WriteToConsole($"Task {taskValue} - after using"); }); } }
public async Task Test() { WriteToConsole("Before using"); using (AmbientStuff.Change(new AmbientStuff(0, ImmutableStack <string> .Empty.Push("Test")))) { WriteToConsole("Inside using - Before DoThings"); var t1 = DoThings(3, 1); //var t2 = DoThings(5, 2); await Task.WhenAll(t1); WriteToConsole("Inside using - After DoThings"); } WriteToConsole("After using"); }