Skip to content

Latest commit

 

History

History
13 lines (7 loc) · 890 Bytes

PH_S029.md

File metadata and controls

13 lines (7 loc) · 890 Bytes

PH_S029 - ThreadLocal in Async Method

Problem

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.

Solution

Consider the use of System.Threading.Tasks.AsyncLocal to share data across an asynchronous flow.

Additional Note

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.