Multithreaded design

I have an instance of a class that can be accessed by multiple threads.

Inside this class there is a variable [ThreadStatic] , which stores various objects.

Now I need a second instance of my class, and I want it to have a separate repository of objects.

Currently, two instances in the same thread will share the same object store. I do not want it.

The only solution I can think of is this:

You have a static IDictionary<int, TObjectStore> , where int is the stream identifier and accessed via any 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 is how can I get rid of the TObjectStore for a specific thread when it ends? I think I correctly assume that with my current implementation, the GC will just pick it up?

thanks

+4
source share
2 answers

The static field is really not in any instance, so I assume that now you need the instance field. In this case, you want ThreadLocal<T> :

 ThreadLocal<SomeType> store = new ThreadLocal<SomeType>( () => { // initializer, used when a new thread accesses the value return ... }); 

This store will be available for the collection along with the copy, as well as any content (if they are not specified anywhere, obviously).

+7
source

Just for more information Marc answer http://blogs.clariusconsulting.net/kzu/a-better-way-to-implement-the-singleton-anti-pattern-for-easier-testing-using-ambientsingleton/

This article discusses different approaches to your problem with code examples.

+2
source

Source: https://habr.com/ru/post/1390635/


All Articles