I discovered ThreadStaticAttribute, and I have a lot of questions about it:
all my previous thread-dependent static information was implemented as a static dictionary in which TKey is Thread, and when I wanted to access it, I used Thread.CurrentThread and that works. But this requires maintenance because if a thread dies, I have to delete the corresponding entry from the dictionary. And I also need to consider thread safety and a lot of other matters.
By using ThreadStaticAttribute, all these matters seem to be solved, but I need to be sure of it. My questions are: do I need to delete the instance held by ThreadStaticAttribute marked fields, somehow, before the thread dies?? Where is the information on that field held?? It is in the instance of a Thread object, or something like that, so that when it is not used anymore, the garbage collector automatically discards it? Are there performance penalties? What ones? Is it faster than using a Keyed collection like I was doing?
I need clarification on how ThreadStaticAttribute works.
No you do not need to delete instances of values help in a field which is tagged with
ThreadStatic. The garbage collector will automatically pick them up when both the thread and the object are no longer reachable by rooted objects.The only exception here is if the value implements
IDisposableand you want to actively dispose of it. In general this is a hard problem to solve for a number of reasons. It’s much simpler to not have values which implementIDisposableand are in aThreadStaticfield.As to where this field is actually stored, it’s somewhat irrelevant. All you need to be concerned about is that it will behave like any other object in .Net. The only two behavior differences are