using ThreadStatic variables with async/await

后端 未结 5 988
独厮守ぢ
独厮守ぢ 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:25

    You could use CallContext.LogicalSetData and CallContext.LogicalGetData, but I recommend you don't because they don't support any kind of "cloning" when you use simple parallelism (Task.WhenAny / Task.WhenAll).

    I opened a UserVoice request for a more complete async-compatible "context", explained in more detail in an MSDN forum post. It does not seem possible to build one ourselves. Jon Skeet has a good blog entry on the subject.

    So, I recommend you use argument, lambda closures, or the members of the local instance (this), as Marc described.

    And yes, OperationContext.Current is not preserved across awaits.

    Update: .NET 4.5 does support Logical[Get|Set]Data in async code. Details on my blog.

提交回复
热议问题