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>
:
ThreadLocal<SomeType> store = new ThreadLocal<SomeType>( () => {
// initializer, used when a new thread accesses the value
return ...
});
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).
Just to provide a bit more information to Marc's answer http://blogs.clariusconsulting.net/kzu/a-better-way-to-implement-the-singleton-anti-pattern-for-easier-testing-using-ambientsingleton/
That article discusses various approaches to your problem, with code examples.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With