我不得不在我的代码中使用AsyncLocal替换ThreadLocal的使用,以便在等待异步操作时保持“环境状态”.
但是,AsyncLocal令人讨厌的行为是它“流动”到子线程.这与ThreadLocal不同.反正有没有阻止这个?
class Program { private static readonly ThreadLocal<string> ThreadState = new ThreadLocal<string>(); private static readonly AsyncLocal<string> AsyncState = new AsyncLocal<string>(); static async Task MainAsync() { ThreadState.Value = "thread"; AsyncState.Value = "async"; await Task.Yield(); WriteLine("After await: " + ThreadState.Value); WriteLine("After await: " + AsyncState.Value); // <- I want this behavIoUr Task.Run(() => WriteLine("Inside child task: " + ThreadState.Value)).Wait(); // <- I want this behavIoUr Task.Run(() => WriteLine("Inside child task: " + AsyncState.Value)).Wait();