Andrew Bullock
Andrew Bullock

Reputation: 37378

Multithreading design pattern

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

Upvotes: 4

Views: 1408

Answers (2)

Victor Kornov
Victor Kornov

Reputation: 66

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.

Upvotes: 2

Marc Gravell
Marc Gravell

Reputation: 1062780

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).

Upvotes: 7

Related Questions