Why does AsyncLocal <T> extend to child threads where ThreadLocal <T> is not?
I had to replace the use of ThreadLocal in my AsyncLocal code so that the "environment" was maintained while waiting for asynchronous operations.
However, AsyncLocal's annoying behavior is that it "flowed" to child threads. This is different from ThreadLocal. Is there any way to prevent this?
class Program { private static readonly ThreadLocal<string> ThreadState = new ThreadLocal<string>(); private static readonly AsyncLocal<string> AsyncState = new AsyncLocal<string>(); static async Task MainAsync() { ThreadState.Value = "thread"; AsyncState.Value = "async"; await Task.Yield(); WriteLine("After await: " + ThreadState.Value); WriteLine("After await: " + AsyncState.Value); // <- I want this behaviour Task.Run(() => WriteLine("Inside child task: " + ThreadState.Value)).Wait(); // <- I want this behaviour Task.Run(() => WriteLine("Inside child task: " + AsyncState.Value)).Wait(); +5