C# AsyncLocal 和CallContext

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 (线程内变量)

 

posted @ 2020-03-05 17:24  Shikyoh  阅读(1077)  评论(0编辑  收藏  举报