When I call WrapperAsync
AsyncLocalContext.Value
returns null. When I run the same code block outside the method, in the Main
method,
AsyncLocal
is ambient data stored on the ExecutionContext
of the current thread. ExecutionContext
is flowed across threads automagically in async/await call chains (see Stephen Toub's blog for details). When the app starts, the default ExecutionContext
is used, but once data is stored via AsyncLocal
, a new ExecutionContext
is created for the current async call chain (see here) and the ambient data is added to it. This new context is propagated to downstream calls.
Stephen Cleary discusses this behavior here (scroll down to the AsyncLocal section) and makes the point:
[AsyncLocal] provides a way for contextual information to flow “down” asynchronous calls. Note that the value does not flow “up”.
This is why AsyncLocal
updates down the call chain are not reflected in upstream methods.