Developer knowledge network · moderated exchange

مجتمع الكود غير الموثوق به

أبحاث المطورين، مجتمع الهندسة العكسية والترميز

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 months ago · 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 months ago · 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 months ago · Jun 28, 2026 7:47 AM
#3

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