为什么AsyncLocal与CallContext不同

时间:2017-01-24 10:10:41

标签: c# multithreading callcontext

运行波纹管代码,您可以看到CallContext和AsyncLocal之间存在不同。

using System;
using System.Runtime.Remoting.Messaging;
using System.Threading;

namespace AsyncLocalIsDifferentThanCallContext
{
    class Program
    {
        public static AsyncLocal<int> AsyncLocal = new AsyncLocal<int>();

        public static int CallContextValue
        {
            get
            {
                var data = CallContext.GetData("CallContextValue");
                if (data == null)
                    return 0;
                return (int) data;
            }
            set { CallContext.SetData("CallContextValue", value); }
        }

        static void Main(string[] args)
        {
            AsyncLocal.Value = 1;
            CallContextValue = 1;
            new Thread(() =>
            {
                Console.WriteLine("From thread AsyncLocal: " + AsyncLocal.Value); // Should be 0 but is 1
                Console.WriteLine("From thread CallContext: " + CallContextValue); // Value is 0, as it should be
            }).Start();
            Console.WriteLine("Main AsyncLocal: " + AsyncLocal.Value);
            Console.WriteLine("Main CallContext: " + CallContextValue);
        }
    }
}

你能解释一下原因吗?

我希望AsyncLocal的值在每个线程中都是唯一的,因为documentation表示它应该表现得像CallContext一样。

1 个答案:

答案 0 :(得分:1)

你想到ThreadLocalAsyncLocal可以像

那样在线程中流动
  

由于基于任务的异步编程模型倾向于抽象使用线程,因此AsyncLocal实例可用于跨线程持久保存数据