简体   繁体   English

在所有线程完成之前不要退出方法

[英]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. 我已经阅读了一些有关Await关键字的信息,但并不太了解如何使用它。

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) 使用await关键字(不知道如何或是否合适)

  • dont use Thread class at all. 根本不要使用Thread类。 use Parallel.X or similar 使用Parallel.X或类似的

Environment 环境

  • C# C#
  • Visual Studio 2012 Visual Studio 2012
  • .Net 4 .Net 4

Use Thread.Join() to make your main thread wait for the child threads, or use Tasks and the Task.WaitAll() method. 使用Thread.Join()使您的主线程等待子线程,或者使用Tasks和Task.WaitAll()方法。

Here is a quick example of you could use Task and await to do something similar. 这是一个简单的示例,您可以使用Task并等待执行类似的操作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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