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();

运行结果:

C#  AsyncLocal 和CallContext

 

 

 

 

 这是栈逃逸

CallContext   (线程上下文)

LogicalCallContext

ExecutionContext(执行上下文)

AsyncLocal  (多线程共享变量)

ThreadLocal (线程内变量)

 

相关文章:

  • 2022-01-01
  • 2022-01-10
  • 2022-12-23
  • 2023-03-02
  • 2022-12-23
  • 2022-12-23
  • 2022-01-30
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-07-25
  • 2021-12-01
  • 2021-08-14
相关资源
相似解决方案