I have an instance of a class that can be accessed by multiple threads.
Inside this class is a [ThreadStatic] variable which stores various objects.
I now need a second instance of my class, and I want it to have a separate object store inside it.
Currently, two instances in the same thread will share the same object store. I do not want this.
The only solution I can think of is:
Have a static IDictionary<int, TObjectStore> where the int is the thread id, and access this via some method or getter:
static TObjectStore ObjectStore {
get {
// create the instance here if its the first-access from this thread, with locking etc. for safety
return objectStore[Thread.CurrentThread.Id];
}
}
The problem with this though is how do I dispose of the TObjectStore for a particular thread when it ends? I think im right in assuming that with my current implementation, the GC will simply pick it up?
Thanks
A static field isn’t really in any instance, so I assume you now need an instance field. In that case, you want a
ThreadLocal<T>:This store will be available for collection along with the instance, as will any contents (as long as they aren’t referenced anywhere else, obviously).