使用ThreadStatic并在每次await完成后设置上下文“是一种选择吗”? 是否还有其他方法?
public async void Test()
{
// This is in Thread 1
Foo foo = new Foo();
Context.context = "context1"; // This is ThreadStatic
string result = await foo.CallAsynx();
// This is most likely Thread 2
Context.context = "context1"; // This might be a different thread and so resetting context
}
如果我不想使用ThreadStatic,还有其他的方法吗?
ThreadStatic
线程吗? 你可以通过CallContext.LogicalSetData/LogicalGetData
流传你的全局状态变量。参考链接:https://dev59.com/3H3aa4cB1Zd3GeqPeYio - noseratio - open to workfoo.CallAsynx(context);
。这是 ASP.NET MVC 的做法。 - Paulo Morgado