运行下面的代码,您可以看到 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 的值对于每个线程都是唯一的,因为文档说它应该表现得像 CallContext 一样。