.NET 中异步操作的线程静态变量

发布于 2024-07-16 07:33:52 字数 134 浏览 8 评论 0原文

有没有办法将 ThreadStatic 变量从一个线程传输到另一个线程? 我有一堆 ThreadStatic 变量,现在我正在将操作转换为异步操作,我希望能够将它们从第一个线程(设置它们的位置)“传输”到回调线程(将在其中读取它们) )。 这可能吗?

Is there any way to have ThreadStatic variables be transferred from one thread to another? I have a bunch of ThreadStatic variables, and now that I am converting my operation to be asynchronous, I want to be able to "transfer" them from the first thread (where they are set) to the callback thread (where they will be read). Is this possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

阳光下慵懒的猫 2024-07-23 07:33:52

不可以。您需要通过异步调用保留操作的上下文。 这就是大多数异步调用中“state”参数的用途。

ThreadStatic 变量在某些情况下很有用,但我通常对它们保持警惕。 除非您确实知道不需要任何类型的线程敏捷性,否则最好以更明确的方式保持状态。

No. You need to keep the context of the operation with the asynchronous call. That's what the "state" parameter is for on most asynchronous calls.

ThreadStatic variables can be useful in some situations, but I'm generally wary of them. Unless you really know that you don't need any kind of thread agility, it's better to keep the state in a more explicit fashion.

七颜 2024-07-23 07:33:52

最好的方法是向您的操作传递一些对象,它可以在回调之前设置您的 threadstatic 变量。 无法从调用线程直接访问 threadstatic 变量。

话虽这么说,我会重新考虑你的设计。 如果您希望该变量可从多个线程使用,则它可能不应该是线程静态变量。 它可能应该通过其他方式进行管理。

The best approach for this would be to pass your operation some object, one which it can set your threadstatic variable prior to calling back. There is no way to directly access the threadstatic variable from the calling thread.

That being said, I'd rethink your design. If you want the variable to be available from multiple threads, it probably shouldn't be a threadstatic variable. It probably should be managed by some other means.

生生不灭 2024-07-23 07:33:52

如果您需要这样做,您可能不希望它们成为ThreadStatic。 您可以创建一个静态 Dictionary 并将线程 ID 映射到变量。

If you need to do so, you probably don't want them to be ThreadStatic. You could make a static Dictionary<int,VarType> and map thread IDs to variables.

他夏了夏天 2024-07-23 07:33:52

在我看来,最好的方法是使用 state 参数,正如乔恩所说。 但是,如果有必要,您可以查看 系统.Runtime.Remoting.Contexts.Context

It seems to me that the best way would be to use the state parameter, as Jon said. However, if necessary, you could look at System.Runtime.Remoting.Contexts.Context.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文