解决办法对于WaitHandle.WaitAll的64句柄限制? [英] Workaround for the WaitHandle.WaitAll 64 handle limit?

查看:884
本文介绍了解决办法对于WaitHandle.WaitAll的64句柄限制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序通过 ThreadPool.QueueUserWorkItem 我通过多个保持跟踪派生不同的小工作线程负载的ManualResetEvent 实例。我用的是 WaitHandle.WaitAll的方法,从关闭,直到这些线程完成挡住了我的申请。

我以前从未有过任何问题,但是,由于我的应用程序创建,即更多的线程多负载下的到来,我现在开始得到这个异​​常:

WaitHandles必须小于或等于64 - 丢失的文档

什么是最好的替代解决方案是这样?

code段

 列表<&的AutoResetEvent GT;事件=新的List<&的AutoResetEvent GT;();//的多个实例...
VAR EVT =新的AutoResetEvent(假);
events.Add(EVT);
ThreadPool.QueueUserWorkItem(代表
{
    // 做工作
    evt.Set();
});...
WaitHandle.WaitAll的(events.ToArray());

解决方法

  INT THREADCOUNT = 0;
ManualResetEvent的成品=新的ManualResetEvent(假);...
Interlocked.Increment(REF THREADCOUNT);
ThreadPool.QueueUserWorkItem(代表
{
    尝试
    {
         // 做工作
    }
    最后
    {
        如果(Interlocked.Decrement(REF THREADCOUNT)== 0)
        {
             finished.Set();
        }
    }
});...
finished.WaitOne();


解决方案

创建保持运行的任务数的轨道的变量:

  INT numberOfTasks = 100;

创建了一个信号:

  ManualResetEvent的信号=新的ManualResetEvent(假);

递减每当一个任务完成的任务数:

 如果(Interlocked.Decrement(REF numberOftasks)== 0)
{

如果没有任务剩余,设置信号:

  signal.Set();
}

同时,在其他地方,等待信号来进行设置:

  signal.WaitOne();

My application spawns loads of different small worker threads via ThreadPool.QueueUserWorkItem which I keep track of via multiple ManualResetEvent instances. I use the WaitHandle.WaitAll method to block my application from closing until these threads have completed.

I have never had any issues before, however, as my application is coming under more load i.e. more threads being created, I am now beginning to get this exception:

WaitHandles must be less than or equal to 64 - missing documentation

What is the best alternative solution to this?

Code Snippet

List<AutoResetEvent> events = new List<AutoResetEvent>();

// multiple instances of...
var evt = new AutoResetEvent(false);
events.Add(evt);
ThreadPool.QueueUserWorkItem(delegate
{
    // do work
    evt.Set();
});

...
WaitHandle.WaitAll(events.ToArray());

Workaround

int threadCount = 0;
ManualResetEvent finished = new ManualResetEvent(false);

...
Interlocked.Increment(ref threadCount);
ThreadPool.QueueUserWorkItem(delegate
{
    try
    {
         // do work
    }
    finally
    {
        if (Interlocked.Decrement(ref threadCount) == 0)
        {
             finished.Set();
        }
    }
});

...
finished.WaitOne();

解决方案

Create a variable that keeps track of the number of running tasks:

int numberOfTasks = 100;

Create a signal:

ManualResetEvent signal = new ManualResetEvent(false);

Decrement the number of tasks whenever a task is finished:

if (Interlocked.Decrement(ref numberOftasks) == 0)
{

If there is no task remaining, set the signal:

    signal.Set();
}

Meanwhile, somewhere else, wait for the signal to be set:

signal.WaitOne();

这篇关于解决办法对于WaitHandle.WaitAll的64句柄限制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆