Based on everything I have read the following Test method should pass. I am trying to understand why it fails. The first assert in the private async method passes as expected. However once the task is returned and waited. The value that was set in the CallContext is now null when retrieved.
[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");
});
}
Methods decorated with the async
keyword create a child context when called. Any changes made to this child context are not propagated to the parent context.
Thus, PerformSimpleAsyncWork
gets a child context that can see anything that was put into the context by the caller, but any changes that it makes will not be available to the caller (LogicalCallContextBlockingTest
).
Stephen Cleary has a good writeup on this behavior if you want more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With