Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logical CallContext values not flowing using async Tasks

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");

            });   
    }
like image 501
Michael M. Avatar asked Oct 03 '14 17:10

Michael M.


1 Answers

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.

like image 53
Brandon Avatar answered Nov 14 '22 21:11

Brandon