AsyncLocal<string> data = new AsyncLocal<string>(); data.Value = "lcc"; for (int i = 0; i < 20; i++) { var current = i; Thread.Sleep(500 * current); Task.Run(() => { Console.WriteLine($"-----[{current}]-----Begin:{data.Value}"); data.Value = current + "lcc"; Console.WriteLine($"-----[{current}]-----End:{data.Value}"); }); Console.WriteLine($"-----[{current}]-----Current:{data.Value}"); } Console.ReadLine();
运行结果:
这是栈逃逸
CallContext (线程上下文)
LogicalCallContext
ExecutionContext(执行上下文)
AsyncLocal (多线程共享变量)
ThreadLocal (线程内变量)