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
source share
1 answer

AsyncLocal stores data in the execution context, which is automatically processed by most APIs (including Task.Run ).

One way to prevent explicit flow suppression if necessary:

 using (ExecutionContext.SuppressFlow()) { Task.Run(...); } 
+8
source

All Articles