在使用 Task.Run() 和 Async 方法时,我正在尝试使用 AsyncLocal 作为 Thread 本地存储的替代品。我遇到的问题是我需要下面的代码来打印
from t1 t1
from t1 t1
from t2 t2
from t2 t2
如果使用 Thread 本地存储,这将是行为,但我得到的是这个输出。
from t1 t1
from t1 t1
from t2 t1
from t2 t1
示例代码:
public class ClientClass {
public static void Main()
{
AsyncLocal<string> _asyncLocalString = new AsyncLocal<string>();
var t1 = Task.Run( async () => {
string a = _asyncLocalString.Value;
if (a == null) {
_asyncLocalString.Value = "t1";
}
a = _asyncLocalString.Value;
Console.WriteLine("from t1 " + a);
await Task.Delay(10);
string b = _asyncLocalString.Value;
Console.WriteLine("from t1 " + b);
var t2 = Task.Run( async () => {
string aa = _asyncLocalString.Value;
if (aa == null) {
_asyncLocalString.Value = "t2";
}
aa = _asyncLocalString.Value;
Console.WriteLine("from t2 " + aa);
await Task.Delay(10);
string bb = _asyncLocalString.Value;
Console.WriteLine("from t2 " + bb);
});
await t2;
});
t1.Wait();
}
}