Flowing execution context with AsyncLocal

suggest change

When you need to pass some data from the parent task to its children tasks, so it logically flows with the execution, use AsyncLocal class:

void Main()
{
    AsyncLocal<string> user = new AsyncLocal<string>();
    user.Value = "initial user";
    
    // this does not affect other tasks - values are local relative to the branches of execution flow
    Task.Run(() => user.Value = "user from another task"); 
    
    var task1 = Task.Run(() =>
    {
        Console.WriteLine(user.Value); // outputs "initial user"
        Task.Run(() =>
        {
            // outputs "initial user" - value has flown from main method to this task without being changed
            Console.WriteLine(user.Value);
        }).Wait();

        user.Value = "user from task1";

        Task.Run(() =>
        {
            // outputs "user from task1" - the value flowed into task1,
            // was changed there, and then flowed into this task
            Console.WriteLine(user.Value);
        }).Wait();
    });

    task1.Wait();

    // outputs "initial user" - changes do not propagate back up the execution flow
    Console.WriteLine(user.Value);
}

Note: Setting AsyncLocal<T>.Value in a child context does not change the parent. That is copy-on-write of the value, not copy-on-read. If you flow a reference type and change its properties, other tasks that share that instance still see the mutation. Prefer value types or immutable types.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents