using System.Threading.Tasks;
static AsyncLocal<string> asyncLocal = new();
asyncLocal.Value = "heh";
Console.WriteLine($"Main() before: {asyncLocal.Value}");
Console.WriteLine($"Main() after: {asyncLocal.Value}");
asyncLocal.Value = "heh";
Console.WriteLine($"Main() before suppressed: {asyncLocal.Value}");
Console.WriteLine($"Main() after suppressed: {asyncLocal.Value}");
asyncLocal.Value = "heh";
Console.WriteLine($"Main() before sync: {asyncLocal.Value}");
Console.WriteLine($"Main() after sync: {asyncLocal.Value}");
asyncLocal.Value = "heh";
Console.WriteLine($"Main() before sync suppressed: {asyncLocal.Value}");
Console.WriteLine($"Main() after sync suppressed: {asyncLocal.Value}");
static Task Run(bool synchronous, bool suppress)
using (ExecutionContext.SuppressFlow())
Console.WriteLine($" Run() before 1, synchronous={synchronous}, suppress={suppress}: {asyncLocal.Value}");
Console.WriteLine($" Run() before 2, synchronous={synchronous}, suppress={suppress}: {asyncLocal.Value}");
return TestSynchronous();
var context = ExecutionContext.Capture();
Console.WriteLine($" Test() EC is null: {context is null}");
ExecutionContext.Run(context!, run, null);
Console.WriteLine($" Test() before: {asyncLocal.Value}");
asyncLocal.Value = "hello";
Console.WriteLine($" Test() after: {asyncLocal.Value}");
static Task TestSynchronous()
var context = ExecutionContext.Capture();
Console.WriteLine($" TestSynchronous() EC is null: {context is null}");
ExecutionContext.Run(context!, run, null);
return Task.CompletedTask;
Console.WriteLine($" TestSynchronous() before: {asyncLocal.Value}");
asyncLocal.Value = "hello";
Console.WriteLine($" TestSynchronous() after: {asyncLocal.Value}");