ThreadStatic
, ThreadLocal<T>
, thread data slots, and CallContext.GetData
/ CallContext.SetData
do not work well with async
, since they are thread-specific.
The best alternatives are:
- Passing it as an argument as @PauloMorgado suggested. Equivalently, you could set it as a field member of an object (it's implicitly passed as an argument via
this
); or you could have your lambdas capture the variable (underneath, the compiler will implicitly pass it as an argument viathis
). - Use
HttpContext.Items
(if you are on ASP.NET 4.5). - Use
CallContext.LogicalGetData
/CallContext.LogicalSetData
as @Noseratio suggested. You can only store immutable data in the logical thread context; and it only works on .NET 4.5 and is not available on all platforms (e.g., Win8). - Force all
async
continuations back to the same thread by installing a "main loop" for that thread, such as theAsyncContext
from my AsyncEx library.