Updated on

AsyncLocal<T> stores a value that follows the async flow in C#. We set it once, and every async method we call down the chain can read it, but a change made inside a called async method never travels back up to the caller.

We’ll start with the problem AsyncLocal solves, run two examples that show how its value moves, compare it with ThreadLocal<T>, and finish with the cases where we should use it.

To download the source code for this article, you can visit our GitHub repository.

Let’s dive in!

What Is AsyncLocal in C#?

AsyncLocal<T> is a class in the System.Threading namespace that holds one value for the current async flow. Microsoft Learn describes it as “ambient data that is local to a given asynchronous control flow”.

We read and write that value through its only property, Value. When we set it and then call an async method, the called method sees the same value. So does code we start on a new thread or with Task.Run.

The flow only goes one way. If the called async method changes Value, the change stays inside that method and the async methods it calls. Once it returns, the caller still reads its own value.

That makes AsyncLocal<T> a good home for data that belongs to one request or one operation, such as a correlation ID or the current user, which we would otherwise pass as a parameter through every method.

Behind the scenes, the value lives on the ExecutionContext, which .NET captures when we await, start a thread or call Task.Run.

AsyncLocal as a Way to Modify the ExecutionContext Classย 

During the development of asynchronous .NET applications, we often come across the need to pass values through the entire asynchronous flow. Good examples are data of authenticated users or correlation identifiers for logging that help us identify all logs related to one request.ย 

The obvious solution would be adding additional parameters to our methods and passing these values as an argument. Such an approach can lead to numerous parameters in methods that we don’t necessarily need in each of them and are present only to pass this data to the methods that this method calls. Besides this tramp data, this also leads to unnecessary coupling of the classes.ย 

A better solution would be storing such data in variables or classes accessible from all other classes in the async flow. In other words, to persist data in the particular async flow.

We could store these data in thread-local storage, but task-based asynchronous programming doesn’t guarantee that each task executes on the same thread.

To solve this problem, .NET provides a built-in global context where we can store data specific to single requests. And that is the ExecutionContext class.

To learn more about the differences between Task and Thread, read our article Tasks vs Threads in C#.

The ExecutionContext class attaches to a task and loads into a thread before the execution of a task. The ExecutionContext class serves as a value bag for a single request. We can’t add our own values to the ExecutionContext directly. Instead, we get and set data on it through AsyncLocal fields. We usually declare that field as static, because each AsyncLocal instance holds its own value, and every class in the flow has to read the same instance.

The AsyncLocal Class Implementation

The AsyncLocal class is a generic class, that implements two constructors: parameterless AsyncLocal<T>(), and AsyncLocal<T>(Action<AsyncLocalValueChangedArgs<T>>). The second constructor accepts an Action argument. This action triggers when the instance value changes.

The AsyncLocal class has only one property, Value, which enables us to get or set the data. It doesn’t have any other methods besides the ones inherited from object.

How Does an AsyncLocal Value Flow Through Async Methods?

An AsyncLocal value flows from a caller into the async methods it calls, and a change made inside a called async method is gone once that method returns. Let’s look at two examples that show it.

AsyncLocal Class Value in Async Flow

The AsyncLocalExample class is a simple static class that implements the DoWork() public method. It uses an AsyncLocal<int> field to store the integer value in different async methods that we call in an async flow:ย 

public static class AsyncLocalExample
{
    public static readonly AsyncLocal<int> AsyncLocalInt = new();

    public static async Task DoWork()
    {
        AsyncLocalInt.Value = 1;
        Console.WriteLine($"AsyncLocal value in DoWork method: {AsyncLocalInt.Value}");

        await DoSubTaskLevel1();

        Console.WriteLine($"AsyncLocal value in DoWork method after executing " +
            $"DoSubTaskLevel1 method: {AsyncLocalInt.Value}");
    }

    private static async Task DoSubTaskLevel1()
    {
        Console.WriteLine($"AsyncLocal value when entering DoSubTaskLevel1 method: {AsyncLocalInt.Value}");

        AsyncLocalInt.Value++;
        Console.WriteLine($"AsyncLocal value after changing in DoSubTaskLevel1 method: {AsyncLocalInt.Value}");

        await DoSubTaskLevel2();

        Console.WriteLine($"AsyncLocal value in DoSubTaskLevel1 method after executing " +
            $"DoSubTaskLevel2 method: {AsyncLocalInt.Value}");
    }

    private static async Task DoSubTaskLevel2()
    {
        Console.WriteLine($"AsyncLocal value when entering DoSubTaskLevel2 method: {AsyncLocalInt.Value}");

        AsyncLocalInt.Value++;
        Console.WriteLine($"AsyncLocal value after changing in DoSubTaskLevel2 method: {AsyncLocalInt.Value}");

        await Task.Delay(100);
    }
}

In the DoWork() method, we set the value of AsyncLocalInt to 1. Within this method, we call the child task DoSubTaskLevel1(). The called method increments the value of the AsyncLocalInt and calls yet another child task, DoSubTaskLevel2(), which increments the AsyncLocalInt value again.ย 

Our Program.cs calls await AsyncLocalExample.DoWork();, and in every method execution, we log the value of AsyncLocalInt:

AsyncLocalExample execution:
AsyncLocal value in DoWork method: 1
AsyncLocal value when entering DoSubTaskLevel1 method: 1
AsyncLocal value after changing in DoSubTaskLevel1 method: 2
AsyncLocal value when entering DoSubTaskLevel2 method: 2
AsyncLocal value after changing in DoSubTaskLevel2 method: 3
AsyncLocal value in DoSubTaskLevel1 method after executing DoSubTaskLevel2 method: 2
AsyncLocal value in DoWork method after executing DoSubTaskLevel1 method: 1

We can see that each async method starts with the value its caller had. ExecutionContext is immutable, so setting Value doesn’t change the context in place. It creates a new ExecutionContext that holds the new value, and only the current method and the methods it calls from then on see it. This copy is shallow, and that matters as soon as we store a reference type.

When an async method returns, its caller goes on with the context it had before the call. That happens at async method boundaries only. A regular method without the async keyword that sets Value changes it for its caller too.

Every task in flow changes the value of AsyncLocalInt.ย But when tasks complete, the changed value of AsyncLocalInt is not visible for the parent task and stays as set in this method. We can observe that in the last two lines of the output.ย 

AsyncLocal Class With Value Change Notification Action

The AsyncLocalNotifyExample class follows the execution logic of our AsyncLocalExample class. The difference is that we create an AsyncLocal class with string as a type argument, and we pass the Action that executes when the value of the AsyncLocal class changes:

public static class AsyncLocalNotifyExample
{
    public static readonly AsyncLocal<string> AsyncLocalString = new(AsyncLocalValueChangedAction);

    static Action<AsyncLocalValueChangedArgs<string>> AsyncLocalValueChangedAction =>
        asyncLocalValueChangedArgs => Console.WriteLine($"Current: {asyncLocalValueChangedArgs.CurrentValue}, " +
                               $"Previous: {asyncLocalValueChangedArgs.PreviousValue}, " +
                               $"Thread: {Environment.CurrentManagedThreadId}, " +
                               $"ThreadContextChanged: {asyncLocalValueChangedArgs.ThreadContextChanged}");

    public static async Task DoWork()
    {
        AsyncLocalString.Value = "Enter DoWork method";

        await DoSubTaskLevel1();

        AsyncLocalString.Value = "Exit DoWork method";
    }

    private static async Task DoSubTaskLevel1()
    {
        AsyncLocalString.Value = "Enter DoSubTaskLevel1 method";

        await DoSubTaskLevel2();

        AsyncLocalString.Value = "Exit DoSubTaskLevel1 method";
    }

    private static async Task DoSubTaskLevel2()
    {
        AsyncLocalString.Value = "Enter DoSubTaskLevel2 method";

        await Task.Delay(100);

        AsyncLocalString.Value = "Exit DoSubTaskLevel2 method";
    }
}

The action AsyncLocalValueChangedAction gets triggered whenever the AsyncLocalString value changes. The type parameter of the action is a struct AsyncLocalValueChangedArgs that holds the previous and current values of the AsyncLocalString, as well as the information on whether the thread context changed:

AsyncLocalNotifyExample execution:
Current: Enter DoWork method, Previous: , Thread: 5, ThreadContextChanged: False
Current: Enter DoSubTaskLevel1 method, Previous: Enter DoWork method, Thread: 5, ThreadContextChanged: False
Current: Enter DoSubTaskLevel2 method, Previous: Enter DoSubTaskLevel1 method, Thread: 5, ThreadContextChanged: False
Current: Enter DoSubTaskLevel1 method, Previous: Enter DoSubTaskLevel2 method, Thread: 5, ThreadContextChanged: True
Current: Enter DoWork method, Previous: Enter DoSubTaskLevel1 method, Thread: 5, ThreadContextChanged: True
Current: , Previous: Enter DoWork method, Thread: 5, ThreadContextChanged: True
Current: Enter DoSubTaskLevel2 method, Previous: , Thread: 5, ThreadContextChanged: True
Current: Exit DoSubTaskLevel2 method, Previous: Enter DoSubTaskLevel2 method, Thread: 5, ThreadContextChanged: False
Current: Enter DoSubTaskLevel1 method, Previous: Exit DoSubTaskLevel2 method, Thread: 5, ThreadContextChanged: True
Current: Exit DoSubTaskLevel1 method, Previous: Enter DoSubTaskLevel1 method, Thread: 5, ThreadContextChanged: False
Current: Enter DoWork method, Previous: Exit DoSubTaskLevel1 method, Thread: 5, ThreadContextChanged: True
Current: Exit DoWork method, Previous: Enter DoWork method, Thread: 5, ThreadContextChanged: False
Current: , Previous: Exit DoWork method, Thread: 5, ThreadContextChanged: True
Current: Exit DoWork method, Previous: , Thread: 5, ThreadContextChanged: True
Current: Exit DoSubTaskLevel1 method, Previous: Exit DoWork method, Thread: 5, ThreadContextChanged: True
Current: Exit DoSubTaskLevel2 method, Previous: Exit DoSubTaskLevel1 method, Thread: 5, ThreadContextChanged: True
Current: , Previous: Exit DoSubTaskLevel2 method, Thread: 5, ThreadContextChanged: True

We can see that the action triggers whenever we set the value of the AsyncLocalString. It also triggers when the value changes without us touching it, and ThreadContextChanged tells the two apart. Microsoft Learn says the property is false “if the AsyncLocal<T>.Value property is changed explicitly”, and those are exactly our own assignments in the output.

The True lines are the runtime switching the ExecutionContext for us. When DoSubTaskLevel2() reaches await Task.Delay(100), control goes back up through DoSubTaskLevel1() and DoWork(), and each of them gets its own value back. When the delay finishes, the continuation picks up DoSubTaskLevel2()‘s context again.

The thread number depends on the machine and the run. In ours, every line ran on thread 5, which shows that ThreadContextChanged reports a change of context, not a change of thread.

Our Program.cs calls await AsyncLocalNotifyExample.DoWork(); last, after the other examples in this article, so the last four lines print while the thread pool thread unwinds after the program’s last statement has already run. On a fast exit, some of them may not show up. If we call it earlier, the four lines show up later, among the lines of the examples that run after it.

How Does AsyncLocal Differ From ThreadLocal?

ThreadLocal<T> gives every thread its own copy of a value. AsyncLocal<T> gives every async flow its own copy, and that flow can move between threads.

The difference shows up as soon as our work leaves the current thread. A value we put in a ThreadLocal<T> stays on the thread that set it. Any other thread, whether a new one or the thread pool thread that picks up our code after an await, doesn’t see it.

An AsyncLocal<T> value travels with the ExecutionContext. .NET captures that context when we start a thread, queue work with Task.Run, or await a task, and uses it on whichever thread runs the code next.

So for async code, ThreadLocal<T> is the wrong tool. It still makes sense for data that really belongs to one thread, such as a per-thread cache of an object that isn’t thread-safe.

If we need to, we can stop the flow with ExecutionContext.SuppressFlow(). Code started inside it reads the default value.

Let’s see both in one run:

public static class AsyncLocalVsThreadLocalExample
{
    private static readonly AsyncLocal<string> AsyncLocalString = new();
    private static readonly ThreadLocal<string> ThreadLocalString = new();

    public static async Task DoWork()
    {
        AsyncLocalString.Value = "Set in DoWork";
        ThreadLocalString.Value = "Set in DoWork";

        var thread = new Thread(() =>
            Console.WriteLine($"New thread, AsyncLocal: {AsyncLocalString.Value}, " +
                $"ThreadLocal: {ThreadLocalString.Value ?? "null"}"));
        thread.Start();
        thread.Join();

        Task task;
        using (ExecutionContext.SuppressFlow())
        {
            task = Task.Run(() =>
                Console.WriteLine($"Task.Run with suppressed flow, AsyncLocal: {AsyncLocalString.Value ?? "null"}"));
        }

        await task;
    }
}

The AsyncLocalVsThreadLocalExample class sets the same string on an AsyncLocal<string> and a ThreadLocal<string>, reads both from a new thread, and then starts a Task.Run with the flow suppressed. We call it from Program.cs with await AsyncLocalVsThreadLocalExample.DoWork(); and get:

AsyncLocalVsThreadLocalExample execution:
New thread, AsyncLocal: Set in DoWork, ThreadLocal: null
Task.Run with suppressed flow, AsyncLocal: null

The new thread reads our AsyncLocal value because Thread.Start() passes the ExecutionContext along. Its ThreadLocal slot was never set, so it reads null.

Inside the using block, SuppressFlow() stops Task.Run from capturing the context, and the task reads null as well. We start the task inside the block but await it outside. If we await inside the block instead, leaving the block throws an InvalidOperationException.

The output does not depend on timing: a new thread never shares a ThreadLocal slot with the thread that started it, and both lines print before DoWork() returns.

When to Use AsyncLocalย 

The AsyncLocal generic class doesn’t limit type parameters to simple data types. We can construct it with any argument, such as dictionaries, lists, stacks, etc.ย 

There is a catch with those types. The copy a called method gets is shallow, so if that method changes the object itself, instead of putting a new object in Value, the caller sees the change too:

public static class AsyncLocalReferenceTypeExample
{
    public static readonly AsyncLocal<List<string>> AsyncLocalList = new();

    public static async Task DoWork()
    {
        AsyncLocalList.Value = ["Added in DoWork"];

        await DoSubTask();

        Console.WriteLine($"AsyncLocal list in DoWork method after executing DoSubTask method: " +
            $"{string.Join(", ", AsyncLocalList.Value)}");
    }

    private static async Task DoSubTask()
    {
        AsyncLocalList.Value!.Add("Added in DoSubTask");

        await Task.Delay(100);
    }
}

When we run it, the caller gets the item its child added:

AsyncLocalReferenceTypeExample execution:
AsyncLocal list in DoWork method after executing DoSubTask method: Added in DoWork, Added in DoSubTask

Both methods hold the same List<string>, so the one-way rule from our first example doesn’t protect it. If a called method needs its own version, it should assign a new object to Value. Immutable types such as string or ImmutableList<T> avoid the problem.

The most obvious usage is for storing request-specific data, such as user identity-related data, session data, and transaction identifiers. It is convenient for storing the data for logging, such as correlation ID, which is used in structured logging to trace the flow of the single request through executing methods in different classes.ย 

For data that only lives inside one ASP.NET Core request, HttpContext.Items is the other option worth knowing.

The AsyncLocal class is not appropriate for storing data across unrelated asynchronous operations. Its value follows the async flow, while thread-local storage stays with the thread. Finally, we don’t use the AsyncLocal class for application-wide state. A static field or a singleton service fits that better.

Conclusion

To persist values across the async flow, the AsyncLocal class represents a convenient implementation. It enables writing cleaner code and avoiding using some less elegant solutions to pass the data down the async flow to the methods that may need this data.ย 

However, we should be aware of the inner workings and behavior of the AsyncLocal class, such as persisting value only on the task level where we set the value and down the async flow to its child tasks to avoid unwanted consequences.ย 

Tested with .NET 11 (SDK 11.0.100, runtime 11.0.0) and MSTest 4.5.3.