using ThreadStatic variables with async/await

后端 未结 5 983
独厮守ぢ
独厮守ぢ 2020-12-08 19:21

With the new async/await keywords in C#, there are now impacts to the way (and when) you use ThreadStatic data, because the callback delegate is executed on a different thre

5条回答
  •  眼角桃花
    2020-12-08 20:18

    AsyncLocal provides support for maintaining variables scoped to a particular asynchronous code flow.

    Changing the variable type to AsyncLocal, e.g.,

    private static AsyncLocal Secret = new AsyncLocal();
    

    gives the following, desired output:

    Started on thread [5]
    Secret is [moo moo]
    Was on thread [5]
    Now on thread [6]
    Finished on thread [6]
    Secret is [moo moo]
    

提交回复
热议问题