Developer knowledge network · moderated exchange

UnreliableCode 커뮤니티

개발자 연구, 리버스 엔지니어링 및 코딩 커뮤니티

Knowledge index살다
4Categories
919Threads
2.8K게시물
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.