CallContext booleans do not flow using async

Based on everything I read, the following testing method should pass. I am trying to understand why he is failing. The first statement in the private asynchronous method passes as expected. However, as soon as the task returns and waits. The value that was set in the CallContext is now null on recovery.

[TestMethod] public void LogicalCallContextBlockingTest() { PerformSimpleAsyncWork().Wait(); var result = CallContext.LogicalGetData("test"); Assert.AreEqual(result, "expected"); } private async Task PerformSimpleAsyncWork() { await Task.Run(() => { System.Threading.Thread.Sleep(100); CallContext.LogicalSetData("test", "expected"); var result = CallContext.LogicalGetData("test"); Assert.AreEqual(result, "expected"); }); } 
+5
source share
1 answer

Methods decorated with the async create a child context when called. Any changes made to this child context do not apply to the parent context.

Thus, PerformSimpleAsyncWork receives a child context that can see everything that was placed in the context of the caller, but any changes made to it will not be available to the caller ( LogicalCallContextBlockingTest ).

Stephen Cleary has a good record of this behavior if you need more information.

+9
source

Source: https://habr.com/ru/post/1203959/


All Articles