I have a mainthread and i do create another n-threads. Each of the n-threads is populating a List<String>. When all threads are finished, they are joined, and i would like to have all those n-threads List in a List<List<String>> BUT in the mainthread. The mainthread should be able to operate on that List<List<String>>. Each of the n-threads contributed a List<String>.
I have c# .NET 3.5 and i would like to avoid a static List<List<String>>
Thread t = new Thread(someObjectForThreading.goPopulateList);
list_threads.Add(t);
list_threads.last().start()
all those threads in list_threads go on and populate their List and when they are finished i would like to have something like
//this = mainThread
this.doSomethingWith(List<List<String>>)
Edit: Hmmm is there no a “standard concept” how to solve such a task? Many threads operating on a list and when all joined, the mainthread can proceed with operating on the list.
Edit2: the List<List<String>> listOfLists must not be static. It can be public or private. First i need the n-threads to operate (and lock) the listOfLists, insert their List and after all n-threads are done inserting their lists, i would join the threads and the mainthread could proceed with businesslogic and operate on the listOfLists
i think i will reRead some parts of http://www.albahari.com/threading/ report back
Here’s a simple implementation using wait handles (in the case ManualResetEvent) to allow each worker thread to signal the main thread that it’s done with its work. I hope this is somewhat self explanatory:
Note how I’m only locking while I add each thread’s List to the main list of lists. There is no need to lock the main list for each add, as each thread has its own List. Make sense?
Edit:
The point of using the waithandle is to wait for each thread to complete before working on your list of lists. If you don’t wait, then you run the risk of trying to enumerate one of the List instances while the worker is still adding strings to it. This will cause an InvalidOperationException to be thrown, and your thread(s) will die. You cannot enumerate a collection and simultaneously modify it.