简体   繁体   中英

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:

  • 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

  • C#
  • Visual Studio 2012
  • .Net 4

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM