簡體   English   中英

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

[英]Dont exit a method till all Threads are complete

我有一個要並行執行的方法列表。

我目前有以下代碼:

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

但是我不希望在所有這些線程完成其工作之前返回該方法。

我已經閱讀了一些有關Await關鍵字的信息,但並不太了解如何使用它。

實現上述目標的最佳方法是什么?

一些想法:

  • 創建每個線程並將其添加到列表中,然后在方法末尾循環,以某種方式檢查每個線程是否完整

  • 使用await關鍵字(不知道如何或是否合適)

  • 根本不要使用Thread類。 使用Parallel.X或類似的

環境

  • C#
  • Visual Studio 2012
  • .Net 4

使用Thread.Join()使您的主線程等待子線程,或者使用Tasks和Task.WaitAll()方法。

這是一個簡單的示例,您可以使用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