How to manage Thread Local Storage (TLS) when using TPL?

前端 未结 3 763
别那么骄傲
别那么骄傲 2021-02-14 10:48

I want to store logging context information in TLS so that I can set a value at the entry point, and have that value available in all resulting stacks. This work well, but I als

3条回答
  •  故里飘歌
    2021-02-14 11:24

    There is, of course, yet another alternative: Write a TaskLocal(T) class, like we did, that bases the storage on the current Task, rather than the current Thread. Honestly, I have no idea why Microsoft didn't do this as part of their initial Task implementation.

    Important Implementation note: Because Task code that calls await can be split, and resume as a different TaskId, you also need to do what we also did, and implement a method in TaskLocal(T) that maps new TaskIds to previous ones, then save the original TaskId at the start of the Task, and map it after every await call.

提交回复
热议问题