2014-09-10 69 views
0

我有我想要並行執行的方法列表。不要退出方法,直到所有線程完成

我現在有這樣的代碼:

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關鍵字(不知道如何或如果它是合適的)

  • 根本不使用線程類。使用Parallel.X或類似

環境

  • C#
  • 的Visual Studio 2012
  • 的.Net 4
+0

使用線程你想存儲對新線程的引用並在它們上面調用'Join'。但是,正確的方法需要更多關於你在做什麼的背景。 – 2014-09-10 11:52:34

+0

加入(http://msdn.microsoft.com/en-us/library/95hbf2ta(v=vs.110).aspx)所有這些在函數的末尾 – 2014-09-10 11:53:03

回答

1

使用的Thread.join()讓你的主線程等待子線程,或者使用任務和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; 
    } 
} 
相關問題