将我ThreadStatic变量的值仍然存在时,通过线程池循环? [英] Will values in my ThreadStatic variables still be there when cycled via ThreadPool?

查看:200
本文介绍了将我ThreadStatic变量的值仍然存在时,通过线程池循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ThreadStatic变量来存储一些数据,但我很担心,我店的线程上的数据依然会在那里我完成后,释放回线程池。我是否需要担心之前,我完成了线程清理我的ThreadStatic变量?或者,将传递出来下一个QueueUserWorkItem之前,线程池帮我这个忙?这对我来说是特别重要的,因为我要确保我的应用程序的其他线程有一个干净的石板从ThreadStatic变量方面的工作。谢谢!

I am using ThreadStatic variables to store some data, but I am worried that the data I store on the thread will still be there after I am finished with it and release back to the ThreadPool. Do I need to worry about clearing my ThreadStatic variables before I am finished with the thread? Or will the ThreadPool do this for me before "passing it out" for the next QueueUserWorkItem? This is especially important for me because I need to make sure that other threads in my app have a clean slate to work from in terms of ThreadStatic variables. Thanks!

推荐答案

线程池(设计)保持活着调用之间的线程。这意味着ThreadStatic变量将调用QueueUserWorkItem之间持续。

The thread pool (by design) keeps the threads alive between calls. This means that the ThreadStatic variables will persist between calls to QueueUserWorkItem.

此行​​为也是东西你不应该指望。线程池会(最终自行决定)发行线程回来,让他们结束,并根据需要建造新的线程。

This behavior is also something you should not count on. The ThreadPool will (eventually, at its discretion) release threads back and let them end, and construct new threads as needed.

不过,我怀疑你的设计,如果你遇到了问题与此有关。如果您需要在QueueUserWorkItem使用特定的,确定性的ThreadStatic数据,你的线程程序可能是很好的人选做线程处理自己。 ThreadStatic和线程池并不总是一个伟大的组合 - 你只是不一定有足够的控制(因为线程池管理线程),真正充分利用,并从ThreadStatic变量的好处。你永远不会知道两工作项目是否会在同一个线程,不同的线程,以及threadstatic变量是否应该(再)初始化等。

However, I'd question your design if you're running into problems with this. If you need specific, deterministic ThreadStatic data to be used in QueueUserWorkItem, your threading routines might be good candidates for doing the thread handling yourself. ThreadStatic and the ThreadPool aren't always a great combination - you just don't necessarily have enough control (since the ThreadPool manages the threads) to really take advantage and get benefits from ThreadStatic variables. You'll never know whether two work items will be on the same thread, different threads, and whether the threadstatic variable should be (re)initialized, etc.

这篇关于将我ThreadStatic变量的值仍然存在时,通过线程池循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆