Why does AsyncLocal<T> propagate to child threads whereas ThreadLocal<T> does not?

.net, asynchronous, c#, multithreading

Solution

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

One way to prevent that is to explicitly suppress flow whenever needed:

using (ExecutionContext.SuppressFlow())
{
    Task.Run(...);
}

Problem

I have had to replace the usage of ThreadLocal in my code with AsyncLocal so that the 'ambient state' is maintained when awaiting async operations. However, an annoying behaviour of AsyncLocal is that it is 'flowed' to child threads. This is different to 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(); ```

Original source