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();
运行结果:
Begin 都是 初始值,即使在其他线程中 更改了data.value 其他线程也不会同步,并且主线程中 仍为 lcc
CallContext (线程上下文)
LogicalCallContext
ExecutionContext(执行上下文)
AsyncLocal (多线程共享变量)
ThreadLocal (线程内变量)
来源:https://www.cnblogs.com/shikyoh/p/12421391.html