将我ThreadStatic变量的值仍然存在时,通过线程池循环?将我、线程、变量、存在

由网友(第七次心动)分享简介:我使用ThreadStatic变量来存储一些数据,但我很担心,我店的线程上的数据依然会在那里我完成后,释放回线程池。我是否需要担心之前,我完成了线程清理我的ThreadStatic变量?或者,将传递出来下一个QueueUserWorkItem之前,线程池帮我这个忙?这对我来说是特别重要的,因为我要确保我的应用程序的其他...

我使用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.

阅读全文

相关推荐

最新文章