Unless a synchronization context is used, the code after the await
keyword (the continuation) is potentially run on a different thread than the code before it. Therefore, the two code sections may access different values of a System.Threading.ThreadLocal
.
Consider the use of System.Threading.Tasks.AsyncLocal
to share data across an asynchronous flow.
Mind that under some circumstances that the use of ThreadLocal
in asynchronous methods is safe, such as using it to re-use an instance for computations and not sharing information. For example, consider an instance of the class System.Random
. Encapsulating the instance inside a ThreadLocal
allows the safe use across different asynchronous flows and the underlying threads, unless the same seed inside the asynchronous flow is desired.