Reputation: 2775
I have a list of methods I want to execute in parallel.
I currently have this code:
void MethodTest()
{
new Thread(() => Method1()).Start();
new Thread(() => Method2()).Start();
new Thread(() => Method3()).Start();
new Thread(() => Method4()).Start();
new Thread(() => Method5()).Start();
new Thread(() => Method6()).Start();
}
However I dont want the method to return until all of those threads are finished doing their jobs.
I have read a bit about the Await keyword but dont really understand how to use it.
What is the best way to accomplish the above?
Some thoughts:
create each thread and add it to a list then loop at the end of method checking somehow that each thread is complete
use the await keyword (dont know how or if it is appropriate)
dont use Thread class at all. use Parallel.X or similar
Environment
Upvotes: 0
Views: 460
Reputation: 1607
Use Thread.Join() to make your main thread wait for the child threads, or use Tasks and the Task.WaitAll() method.
Here is a quick example of you could use Task and await to do something similar.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
var taskList = new List<Task<int>>
{
Task<int>.Factory.StartNew(Method1),
Task<int>.Factory.StartNew(Method2)
}.ToArray();
Task.WaitAll(taskList);
foreach (var task in taskList)
{
Console.WriteLine(task.Result);
}
Console.ReadLine();
}
private static int Method2()
{
return 2;
}
private static int Method1()
{
return 1;
}
}
Upvotes: 1
Reputation: 2287
The method
Thread.Join()
is what you need
http://msdn.microsoft.com/en-us/library/system.threading.thread.join(v=vs.110).aspx
Upvotes: 1