Steven Wood
Steven Wood

Reputation: 2775

Dont exit a method till all Threads are complete

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:

Environment

Upvotes: 0

Views: 460

Answers (2)

AndersNS
AndersNS

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

T00rk
T00rk

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

Related Questions