How do the semantics of AsyncLocal differ from the logical call context?

后端 未结 3 1702
逝去的感伤
逝去的感伤 2020-12-12 23:27

.NET 4.6 introduces the AsyncLocal class for flowing ambient data along the asynchronous flow of control. I\'ve previously used CallContext.Logic

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-13 00:23

    There appears to be some semantic difference in timing.

    With CallContext the context change happens when the context for the child thread/task/async method is set up, i.e. when Task.Factory.StartNew(), Task.Run() or async method are called.

    With AsyncLocal the context change (change notification callback being called) happens when the child thread/task/async method actually starts executing.

    The timing difference could be interesting, especially if you want the context object to be cloned when the context is switched. Using different mechanisms could result in different content being cloned: with CallContext you clone the content when the child thread/task is created or async method is called; but with AsyncLocal you clone the content when the child thread/task/async method starts executing, the content of the context object could have been changed by the parent thread.

提交回复
热议问题