Does .NET ThreadPool thread get reset when it goes back to the pool?

前端 未结 3 708
予麋鹿
予麋鹿 2021-02-19 04:10

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 ther

相关标签:
3条回答
  • 2021-02-19 04:12

    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

    When the thread pool reuses a thread, it does not clear the data in thread local storage or in fields that are marked with the ThreadStaticAttribute attribute. Therefore, data that is placed in thread local storage by one method can be exposed to any other method that is executed by the same thread pool thread. A method that accesses a field that is marked with the ThreadStaticAttribute attribute could encounter different data depending on which thread pool thread executes it.

    This is something to be very careful about...

    0 讨论(0)
  • 2021-02-19 04:29

    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.

    0 讨论(0)
  • 2021-02-19 04:34

    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.

    0 讨论(0)
提交回复
热议问题