.NET ThreadPool 线程返回池时是否会重置?
当线程池线程完成时,诸如名称或线程本地数据之类的内容是否会重置? 那么下次线程从池中出来时,它就像全新的一样吗?
是否有关于 ThreadPool 线程这方面的“官方”文档?
When a thread pool thread is done, does stuff like Name or thread local data get reset?
So when the thread comes out of the pool next time, it's like brand new?
Is there an "official" documentation on this aspect of the ThreadPool threads?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它在释放时不会清除线程本地存储,这是需要注意的最重要的方面。
http://msdn.microsoft.com/en-us/library /system.threading.threadpool.aspx
这是一个需要非常小心的事情...
It does NOT clear thread local storage when it's released, which is the most important aspect to note.
http://msdn.microsoft.com/en-us/library/system.threading.threadpool.aspx
This is something to be very careful about...
这是关于 . NET (4)
据我所知,没有重置。
在链接的文档中提到了如何处理这个问题的方法。
This is a very good read on parallel programming and TPL in .NET (4)
As far as I know there is no reset.
In the linked document there is are ways mentioned how to cope with that.
答案是否定的,它不会被重置。但是,您不应该依赖这个事实,因为您的下一个工作项是在新线程上还是在重用线程上执行,这取决于线程池。所以你可能会也可能不会再次看到线程本地存储。由于这个原因,我不建议在线程池上使用线程本地存储。线程池实现是一个内部细节,可能会发生变化。
现实世界的比喻是您每天乘坐的公共汽车。假设由于某种原因您想将包留在公交车上,因为您知道它不会被偷。这是一个坏主意,因为下次您上公共汽车时,您可能找不到您的包。只是因为它可以是不同的巴士。公交车站可能会在线路之间轮换公交车,或者可能会处置旧公交车。就像线程池可以在不通知您的情况下重用或退役线程一样。
The answer is no, it will not get reset. However you should not rely on this fact because it is up to the thread pool whether your next work item will be executed on new thread or on the reused thread. So you may or may not see you Thread Local Storage again. I would not recommend using Thread Local Storage on thread pool for this reason. Thread pool implementation is an internal detail and is a subject to change.
The real world metaphor would be a bus that you take to work everyday. Lets say that for some reason you want to leave your bag on the bus because you know that it will not be stolen. This is a bad idea because next time you get on the bus you may not find your bag. Simply because it can be a different bus. Bus depot may rotate buses between lines or may dispose older buses. Just like thread pool may reuse or retire threads without letting you know.