Sobes.tech
Middle

Is it possible to bind a variable to a thread/task so that each task stores its own value? What are ThreadLocal and AsyncLocal?

sobes.tech AI

Answer from AI

Yes, in C# you can bind a variable to a specific thread or asynchronous task so that each of them holds its own value.

ThreadLocal<T> is a class that allows having a separate variable value for each thread. For example, if you have multiple threads, each will have its independent variable value.

ThreadLocal<int> threadLocal = new ThreadLocal<int>(() => 0);

void Work() {
    threadLocal.Value = Thread.CurrentThread.ManagedThreadId;
    Console.WriteLine(threadLocal.Value);
}

AsyncLocal<T> is similar to ThreadLocal but works in the context of asynchronous operations and preserves the value within the chain of async/await calls, even if threads switch.

AsyncLocal<string> asyncLocal = new AsyncLocal<string>();

async Task WorkAsync() {
    asyncLocal.Value = "Value for this async context";
    await Task.Delay(100);
    Console.WriteLine(asyncLocal.Value); // The value is preserved even after await
}

Thus, ThreadLocal is suitable for multithreaded scenarios, while AsyncLocal is for asynchronous ones, where the thread may change but the context needs to be preserved.