AsyncLocal Value updated to null on ThreadContextChanged

你。 提交于 2019-12-05 01:17:30

What you need to do is: ExecutionContext.SuppressFlow();
That will stop raising event valueChangedHandler when your thread context is lost, as result you will not get NULL values, also it will stop raising event when new ThreadContext is created and data is copied to this.

private static void ValueChanged(AsyncLocalValueChangedArgs<string> obj)
{
    Console.WriteLine(obj.CurrentValue);
}

public static void Main(string[] args)
{
    ExecutionContext.SuppressFlow();
    AsyncLocalContext.Value = "Main";
    Task.Run(() =>
        {
            AsyncLocalContext.Value = "Test1";
        }).Wait();

    Console.WriteLine("Main: " + AsyncLocalContext.Value);
}

Output is:

Main
Test1
Main: Main

If we comment ExecutionContext.SuppressFlow(); then will get this:

Main
Main        -- copied data to Task
Test1
            -- here is NULL when context has lost
Main: Main
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!