运行下面的代码,您可以看到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则是这样做的。
发布于 2017-01-24 13:35:51
你认为ThreadLocal?AsyncLocal可以像它所说的那样在线程间流动。
由于基于任务的异步编程模型倾向于抽象线程的使用,所以AsyncLocal实例可以用于跨线程的持久化数据()。
https://stackoverflow.com/questions/41825375
复制相似问题