Developer knowledge network ยท moderated exchange

Onbetrouwbare Code-gemeenschap

Ontwikkelaarsonderzoek, reverse engineering en coderingsgemeenschap

Knowledge indexLive
4Categories
919Threads
2.8KBerichten
Discussion

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

csharp_async_master
Async & Task Expert
MEMBER
Vertegenwoordiger: 57
Datum van deelname: Mar 2019
Berichten: 18
Bedankt: 40
1 maanden geleden ยท 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
Vertegenwoordiger: 103
Datum van deelname: Apr 2018
Berichten: 40
Bedankt: 24
1 maanden geleden ยท 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
Vertegenwoordiger: 156
Datum van deelname: Jan 2022
Berichten: 10
Bedankt: 16
1 maanden geleden ยท Jun 28, 2026 7:47 AM
#3

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