为什么 AsyncLocal 与 CallContext 不同

Why AsyncLocal is different from 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 表现得那样。

你在想ThreadLocalAsyncLocal 可以像它所说的那样跨线程流动

Because the task-based asynchronous programming model tends to abstract the use of threads, AsyncLocal instances can be used to persist data across threads.