当通过 ThreadPool 循环时,ThreadStatic 变量中的值仍然存在吗?
我正在使用 ThreadStatic 变量来存储一些数据,但我担心在线程上存储的数据在我完成并释放回 ThreadPool 后仍然存在。 在完成线程之前,我是否需要担心清除 ThreadStatic 变量? 或者 ThreadPool 会在为下一个 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
线程池(根据设计)使线程在调用之间保持活动状态。 这意味着 ThreadStatic 变量将在对 QueueUserWorkItem 的调用之间保持不变。
这种行为也是你不应该指望的。 ThreadPool 将(最终自行决定)释放线程并让它们结束,并根据需要构造新线程。
但是,如果您遇到问题,我会质疑您的设计。 如果您需要在 QueueUserWorkItem 中使用特定的、确定性的 ThreadStatic 数据,您的线程例程可能是您自己进行线程处理的良好候选者。 ThreadStatic 和 ThreadPool 并不总是一个很好的组合 - 您只是不一定有足够的控制权(因为 ThreadPool 管理线程)来真正利用 ThreadStatic 变量并从中受益。 您永远不会知道两个工作项是否位于同一线程、不同线程上,以及是否应该(重新)初始化 threadstatic 变量等。
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.
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.
我希望它们会保留在方法之间。 当然,如果有疑问,请在工作方法开始时重置线程静态变量。 或者使用
try
/finally
清除每个工作单元之后的值。(编辑)
很容易证明它们确实存在; 上面的代码很快开始打印大于 0 的数字(如果不同的工作人员被隔离,每次 0 就是我们所期望的):
I expect they would remain between methods. Of course, if in doubt, reset the thread-static variables at the start of your worker method. Or use
try
/finally
to clear the values after each unit-of-work.(edit)
It is pretty easy to prove that they do indeed remain; the above quickly starts printing numbers higher than 0 (where 0 each time is what we would expect if the different workers were isolated):