Search code examples
c#multithreadinglistthread-local-storage

A thread private list but shared with methods


I need to launch multiple threads, but each thread would have its own list. This means, the lists are not to be shared, but they will be accessed by different methods.

class foo()
{
    //put the list definition here as a property?

    public main()
    {
        launchthread(threadMethod1)
    }

    public void threadMethod1()
    {
        // create a list instance here?
        // do something about the list, modify data in it
        threadMethod2();
    }

    public void threadMethod2()
    {
        // do something about list, modify data in it
    }
}

How should I properly define the list, where to put the definition? and is it has anything to do with thread-safe if I only want to have a thread private list?
I am looking for options other than passing the list as parameter for threadmethod2.

Assuming that I don't need to use ConcurrentBag/SynchronizedCollection or worry about the lock stuff?


Solution

  • Am I right that you are goind to start your threads something like this:

    class Foo<T>()
    {
        List<T> TLS;
    
        public main()
        {
            launchThread(threadMethod1)
        }
    
        public void threadMethod1()
        {
            TLS = new List<T>()
            // TLS.Add(); HERE
            threadMethod2();
        }
    
        public void threadMethod2()
        {
            // TLS.Add(); HERE
        }
    }
    

    If so, then it completely thread-safe for you, and you no need in ConcurrentCollection-class in your foo definition, as there is only one thread which will access this variable. You don't need to add the list as a parameter as either threadMethod1 or threadMethod2 are supposed to be instance-methods, and the code inside them will see the same reference of the TLS variable.

    I want to point out that you aren't using default coding standarts for the C# - the class names and method names aren't in CamelCasing, for example. I think that your code needs to be formatted properly.

    Also I want to note that the threadMethod1 or threadMethod2 shouldn't be public as they are called from inside the class only, and you should restrict other classes from using them (if I understood your architecture well).

    Good reference about TLS (thread-local-storage) from comments.