等待所有线程完成,超时

问题描述 投票:0回答:11

我在编写的代码中遇到了一个常见模式,我需要等待组中的所有线程完成并超时。超时应该是 all 线程完成所需的时间,因此简单地为每个线程执行

Thread.Join(timeout)
是行不通的,因为可能的超时是
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);

不过,似乎应该有一个更简单的惯用语来形容这种事情。

c# multithreading
11个回答
29
投票

我仍然认为使用 Join 更简单。记录预期完成时间(现在+超时),然后循环执行

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

21
投票

使用 .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

12
投票

这并没有回答问题(没有超时),但我做了一个非常简单的扩展方法来等待集合的所有线程:

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

10
投票

既然问题被提出了,我将继续发布我的解决方案。

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

9
投票

我突然想到,为什么不直接使用 Thread.Join(timeout) 并从总超时中删除加入所花费的时间?

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

编辑:代码现在不再那么伪了。不明白为什么当你修改+4的答案完全相同,只是不那么详细时,你会修改答案-2。


7
投票

这可能不适合您,但如果您可以使用 .NET 的并行扩展,那么您可以使用

Task
而不是原始线程,然后使用
Task.WaitAll()
等待它们完成。


1
投票

我读了《C# 4.0: The Complete Reference of 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();
        }
    }

0
投票

我想弄清楚如何做到这一点,但我无法从谷歌得到任何答案。 我知道这是一个旧线程,但这是我的解决方案:

使用以下类:

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() 在继续之前

0
投票

可能的解决方案:

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 是项目列表,每个项目都需要在单独的线程中处理。


0
投票

这是一个受 Martin v. Löwis 的答案启发的实现:

/// <summary>
/// Blocks the calling thread until all threads terminate, or the specified
/// time elapses. Returns true if all threads terminated in time, or false if
/// at least one thread has not terminated after the specified amount of time
/// elapsed.
/// </summary>
public static bool JoinAll(IEnumerable<Thread> threads, TimeSpan timeout)
{
    ArgumentNullException.ThrowIfNull(threads);
    if (timeout < TimeSpan.Zero)
        throw new ArgumentOutOfRangeException(nameof(timeout));

    Stopwatch stopwatch = Stopwatch.StartNew();
    foreach (Thread thread in threads)
    {
        if (!thread.IsAlive) continue;
        TimeSpan remaining = timeout - stopwatch.Elapsed;
        if (remaining < TimeSpan.Zero) return false;
        if (!thread.Join(remaining)) return false;
    }
    return true;
}

为了测量剩余时间,它使用

DateTime.Now
 代替 
Stopwatch
Stopwatch
组件对系统范围的时钟调整不敏感。

使用示例:

bool allTerminated = JoinAll(new[] { thread1, thread2 }, TimeSpan.FromSeconds(10));

timeout
必须为正数或零
TimeSpan
。不支持
Timeout.InfiniteTimeSpan
常量。


0
投票

我尝试过以下代码。运行多线程

using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
 
public class Program {
    
    public static void Main() {
        List<Thread> threads=new List<Thread>();
        Program prog = new Program();
        for(int i=1; i<=26; i++){
            // Create a new thread and start it
            
            Thread thread = new Thread(() => prog.Funthmeth(i));
            //prog.Funthmeth(i);
            thread.Start();
            threads.Add(thread);
        }
        threads.WaitAll();
    }
 
   
    public void Funthmeth(int inpu)
    {
        char c = Convert.ToChar(64 + inpu);
        for(int i=1; i<=4; i++)
        {
             Console.WriteLine (c + " - " + i);
        }
       
    }
    
}

public static class ThreadExtension
    {
        public static void WaitAll(this IEnumerable<Thread> threads)
        {
            if(threads!=null)
            {
                foreach(Thread thread in threads)
                { thread.Join(); }
            }
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.