gpt4 book ai didi

c# - 如何在 C# 中跨异步等待模型维护线程上下文?

转载 作者:行者123 更新时间:2023-11-30 13:16:48 25 4
gpt4 key购买 nike

每次等待完成时是否使用 ThreadStatic 和设置上下文“一个选项”?还有别的办法吗?

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 , ThreadLocal<T> ,线程数据槽,和CallContext.GetData/CallContext.SetData不适用于 async ,因为它们是特定于线程的。

最好的选择是:

  1. 按照@PauloMorgado 的建议将其作为参数传递。同样,您可以将其设置为对象的字段成员(它通过 this 作为参数隐式传递);或者您可以让您的 lambda 捕获变量(在下面,编译器将通过 this 将其作为参数隐式传递)。
  2. 使用HttpContext.Items (如果您使用的是 ASP.NET 4.5)。
  3. 使用CallContext.LogicalGetData/CallContext.LogicalSetData正如@Noseratio 建议的那样。您只能在逻辑线程上下文中存储不可变数据;它仅适用于 .NET 4.5,并非在所有平台(例如 Win8)上都可用。
  4. 强制所有async通过为该线程安装一个“主循环”,继续回到同一个线程,例如 AsyncContext from my AsyncEx library .

关于c# - 如何在 C# 中跨异步等待模型维护线程上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23555255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com