Developer knowledge network ยท moderated exchange

Komunitas Kode Tidak Dapat Diandalkan

Riset Pengembang, Rekayasa Terbalik & Komunitas Pengkodean

Knowledge indexHidup
4Categories
919Threads
2.8KPostingan
Discussion

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

csharp_async_master
Async & Task Expert
MEMBER
Reputasi: 57
Tanggal Bergabung: Mar 2019
Postingan: 18
Terima kasih: 40
1 bulan yang lalu ยท 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
Reputasi: 103
Tanggal Bergabung: Apr 2018
Postingan: 40
Terima kasih: 24
1 bulan yang lalu ยท 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
Reputasi: 156
Tanggal Bergabung: Jan 2022
Postingan: 10
Terima kasih: 16
1 bulan yang lalu ยท Jun 28, 2026 7:47 AM
#3

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