Developer knowledge network · moderated exchange

UnreliableCode コミュニティ

開発者リサーチ、リバース エンジニアリング、コーディング コミュニティ

Discussion

ThreadLocal<T> vs AsyncLocal<T>: How execution context flows across async/await boundaries [StackOverflow Architecture Guide]

csharp_async_master
Async & Task Expert
MEMBER
担当者: 57
参加日: Mar 2019
投稿: 18
ありがとう: 40
1 か月前 · Jun 27, 2026 9:30 PM
#1

Why ThreadLocal<T> fails when used in asynchronous C# code:

When execution resumes after an await, the continuation frequently runs on a different thread from the .NET ThreadPool. ThreadLocal<T> stores data on the physical OS thread, losing your context!

AsyncLocal<T> Context Flow:

CSHARP
public static AsyncLocal<string> CorrelationId = new();

async Task ProcessRequestAsync()
{
    CorrelationId.Value = Guid.NewGuid().ToString(); // Flows automatically across all awaited child tasks!
    await StepOneAsync();
    await StepTwoAsync();
}

AsyncLocal<T> travels with the logical ExecutionContext, ensuring telemetry correlation IDs flow across thread pool thread transitions!

dotnet_runtime_architect
.NET Core Specialist
MEMBER
担当者: 103
参加日: Apr 2018
投稿: 40
ありがとう: 24
1 か月前 · Jun 28, 2026 2:07 AM
#2

AsyncLocal<T> is the backbone of distributed tracing in OpenTelemetry, ASP.NET Core HttpContextAccessor, and Serilog logging contexts.

channel_concurrency
Reactive & Pipeline
MEMBER
担当者: 156
参加日: Jan 2022
投稿: 10
ありがとう: 16
1 か月前 · Jun 28, 2026 7:47 AM
#3

Keep objects stored in AsyncLocal small and immutable because context cloning occurs on execution forks.