How can I create multiple threads and wait for all of them to complete?
If you don't want to use the Task class (for instance, in .NET 3.5) you can just start all your threads, and then add them to the list and join them in a foreach loop.
Example:
List<Thread> threads = new List<Thread>();
// Start threads
for(int i = 0; i<10; i++)
{
int tmp = i; // Copy value for closure
Thread t = new Thread(() => Console.WriteLine(tmp));
t.Start;
threads.Add(t);
}
// Await threads
foreach(Thread thread in threads)
{
thread.Join();
}
In .NET 4.0, you can use the Task Parallel Library.
In earlier versions, you can create a list of Thread
objects in a loop, calling Start
on each one, and then make another loop and call Join
on each one.