C# Reference ยท Async and Concurrency
ThreadLocal<T> and AsyncLocal<T>
Reference for ThreadLocal<T>, [ThreadStatic] and AsyncLocal<T> in C#: per-thread and per-async-flow values, how they differ across await and Task.Run.
Sometimes a value should be "global" for a piece of work but separate for each concurrent piece of work: a request id for logging, a random-number generator per thread, a transaction. .NET offers three tools. [ThreadStatic] and ThreadLocal<T> keep one value per thread. AsyncLocal<T> keeps one value per asynchronous flow: it follows your code across await, even when the continuation resumes on a different thread.
Because async code hops between threads, per-thread storage is almost never right for it. Use AsyncLocal<T> for ambient context in async code and ThreadLocal<T> for caches tied to the physical thread.
static readonly AsyncLocal<string?> RequestId = new(); RequestId.Value = "req-42"; await Task.Delay(1); Console.WriteLine(RequestId.Value); // still "req-42"
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public class ThreadLocal<T> : IDisposable { public ThreadLocal(); public ThreadLocal(Func<T> valueFactory); public ThreadLocal(Func<T> valueFactory, bool trackAllValues); public T Value { get; set; } public bool IsValueCreated { get; } public IList<T> Values { get; } // requires trackAllValues: true } public sealed class AsyncLocal<T> { public AsyncLocal(); public AsyncLocal(Action<AsyncLocalValueChangedArgs<T>>? valueChangedHandler); public T Value { get; set; } } [ThreadStatic] private static int s_field; // attribute on a static field
| Name | Description |
|---|---|
valueFactory |
Creates a thread's initial value on first access. Without it, the value is default. |
trackAllValues |
Keeps every thread's value reachable via Values; needed to aggregate or dispose them. |
valueChangedHandler |
Called when the value changes, including when the execution context switches. |
Returns: Value returns the current thread's (or flow's) value.
Errors: reading Values without trackAllValues: true throws InvalidOperationException; using a ThreadLocal<T> after Dispose throws ObjectDisposedException.
Usage notes
- Thread-local values do not follow
await. After anawait, your code may run on another thread and see a differentThreadLocal<T>value. UseAsyncLocal<T>inasynccode. AsyncLocal<T>copies on the way down, never up. A child task starts with the parent's value; changing it there does not change the parent's. Likewise a change inside anasyncmethod is not visible to the caller after it returns.- Store immutable values in
AsyncLocal<T>. Because contexts are copied, mutating a shared object changes it for everyone; assigning a new object changes only the current flow. [ThreadStatic]initializers lie.[ThreadStatic] static int x = 5;runs only on the thread that triggered the static constructor; every other thread starts with0. UseThreadLocal<T>with a factory, or lazy-check fordefault.- Thread-pool threads are reused. A
[ThreadStatic]value written by one work item is still there for the next item on that thread, a classic source of data leaks between requests. Clear it or avoid it. ThreadLocal<T>isIDisposableand slower than[ThreadStatic]. Dispose it, and be aware that tracking values keeps them alive.- Suppressing the flow.
ExecutionContext.SuppressFlow()stopsAsyncLocal<T>values from flowing into new tasks and threads; useful for long-lived background work started from a request. - Do not use it as a hidden parameter for business logic. Ambient context is best for cross-cutting concerns such as logging scopes and tracing ids.
- Random.Shared is already thread-safe; you rarely need a
ThreadLocal<Random>today.
Related
- Thread, ThreadPool, SynchronizationContext, Lazy
- Lessons: Threads, Async and await