【发布时间】:2017-05-05 22:01:59
【问题描述】:
我不得不用 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();
【问题讨论】:
标签: c# .net multithreading asynchronous