簡體   English   中英

C#:等待所有線程完成

[英]C#: Waiting for all threads to complete

我正在編寫我正在編寫的代碼中的常見模式,我需要等待組中的所有線程完成,並且超時。 超時應該是所有線程完成所需的時間,因此簡單地為每個線程執行thread.Join(timeout)將不起作用,因為可能的超時是超時* numThreads。

現在我做類似以下的事情:

var threadFinishEvents = new List<EventWaitHandle>();

foreach (DataObject data in dataList)
{
    // Create local variables for the thread delegate
    var threadFinish = new EventWaitHandle(false, EventResetMode.ManualReset);
    threadFinishEvents.Add(threadFinish);

    var localData = (DataObject) data.Clone();
    var thread = new Thread(
        delegate()
        {
            DoThreadStuff(localData);
            threadFinish.Set();
        }
    );
    thread.Start();
}

Mutex.WaitAll(threadFinishEvents.ToArray(), timeout);

但是,對於這種事情,似乎應該有一個更簡單的習語。

我仍然認為使用Join更簡單。 記錄預期的完成時間(如現在+超時),然后在循環中執行

if(!thread.Join(End-now))
    throw new NotFinishedInTime();

使用.NET 4.0,我發現System.Threading.Tasks更容易使用。 這是旋轉等待循環,對我來說可靠。 它會阻塞主線程,直到完成所有任務。 還有Task.WaitAll ,但這對我來說並不總是有用

        for (int i = 0; i < N; i++)
        {
            tasks[i] = Task.Factory.StartNew(() =>
            {               
                 DoThreadStuff(localData);
            });
        }
        while (tasks.Any(t => !t.IsCompleted)) { } //spin wait

由於問題得到了解決,我將繼續發布我的解決方案。

using (var finished = new CountdownEvent(1)) 
{ 
  for (DataObject data in dataList) 
  {   
    finished.AddCount();
    var localData = (DataObject)data.Clone(); 
    var thread = new Thread( 
        delegate() 
        {
          try
          {
            DoThreadStuff(localData); 
            threadFinish.Set();
          }
          finally
          {
            finished.Signal();
          }
        } 
    ); 
    thread.Start(); 
  }  
  finished.Signal(); 
  finished.Wait(YOUR_TIMEOUT); 
} 

在我的腦海中,你為什么不只是Thread.Join(超時)並從總超時中刪除加入所花費的時間?

// pseudo-c#:

TimeSpan timeout = timeoutPerThread * threads.Count();

foreach (Thread thread in threads)
{
    DateTime start = DateTime.Now;

    if (!thread.Join(timeout))
        throw new TimeoutException();

    timeout -= (DateTime.Now - start);
}

編輯:現在代碼更少偽。 不明白為什么你會修改答案-2當你修改的答案+4完全相同,只是不那么詳細。

這不回答問題(沒有超時),但我做了一個非常簡單的擴展方法來等待集合的所有線程:

using System.Collections.Generic;
using System.Threading;
namespace Extensions
{
    public static class ThreadExtension
    {
        public static void WaitAll(this IEnumerable<Thread> threads)
        {
            if(threads!=null)
            {
                foreach(Thread thread in threads)
                { thread.Join(); }
            }
        }
    }
}

然后你只需致電:

List<Thread> threads=new List<Thread>();
//Add your threads to this collection
threads.WaitAll();

這可能不是您的選擇,但如果您可以使用.NET的並行擴展,那么您可以使用Task而不是原始線程,然后使用Task.WaitAll()等待它們完成。

我讀過C#4.0:Herbert Schildt的完整參考書。 作者使用join來提供解決方案:

class MyThread
    {
        public int Count;
        public Thread Thrd;
        public MyThread(string name)
        {
            Count = 0;
            Thrd = new Thread(this.Run);
            Thrd.Name = name;
            Thrd.Start();
        }
        // Entry point of thread.
        void Run()
        {
            Console.WriteLine(Thrd.Name + " starting.");
            do
            {
                Thread.Sleep(500);
                Console.WriteLine("In " + Thrd.Name +
                ", Count is " + Count);
                Count++;
            } while (Count < 10);
            Console.WriteLine(Thrd.Name + " terminating.");
        }
    }
    // Use Join() to wait for threads to end.
    class JoinThreads
    {
        static void Main()
        {
            Console.WriteLine("Main thread starting.");
            // Construct three threads.
            MyThread mt1 = new MyThread("Child #1");
            MyThread mt2 = new MyThread("Child #2");
            MyThread mt3 = new MyThread("Child #3");
            mt1.Thrd.Join();
            Console.WriteLine("Child #1 joined.");
            mt2.Thrd.Join();
            Console.WriteLine("Child #2 joined.");
            mt3.Thrd.Join();
            Console.WriteLine("Child #3 joined.");
            Console.WriteLine("Main thread ending.");
            Console.ReadKey();
        }
    }

我想弄清楚如何做到這一點,但我無法從谷歌得到任何答案。 我知道這是一個舊線程,但這是我的解決方案:

使用以下類:

class ThreadWaiter
    {
        private int _numThreads = 0;
        private int _spinTime;

        public ThreadWaiter(int SpinTime)
        {
            this._spinTime = SpinTime;
        }

        public void AddThreads(int numThreads)
        {
            _numThreads += numThreads;
        }

        public void RemoveThread()
        {
            if (_numThreads > 0)
            {
                _numThreads--;
            }
        }

        public void Wait()
        {
            while (_numThreads != 0)
            {
                System.Threading.Thread.Sleep(_spinTime);
            }
        }
    }
  1. 在執行線程之前調用Addthreads(int numThreads)。
  2. 每個完成后調用RemoveThread()。
  3. 在繼續之前,在等待所有線程完成的位置使用Wait()

可能的方法:

var tasks = dataList
    .Select(data => Task.Factory.StartNew(arg => DoThreadStuff(data), TaskContinuationOptions.LongRunning | TaskContinuationOptions.PreferFairness))
    .ToArray();

var timeout = TimeSpan.FromMinutes(1);
Task.WaitAll(tasks, timeout);

假設dataList是項目列表,每個項目需要在單獨的線程中處理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM