单线程上的线程WaitHandle

时间:2011-07-19 02:07:34

标签: c# .net windows multithreading parallel-processing

我的代码是

public static void Invoke(Action[] Actions)
{
    Thread[] threadArray = new Thread[Actions.Length];
    for (int i = 0; i < Actions.Length; i++)
    {
        threadArray[i] = new Thread(() =>
        {
            Actions[i].Invoke();
        });
        threadArray[i].Start();
    }
}

public static void WaitAll()
{

}

public static void WaitAny()
{

}

我想等待所有线程完成,并在任何线程完成时收到通知,

WaitAnyWaitAll

类似

但是waithandles只能在线程池上使用,找不到任何在单线程上使用的例子。

我的应用程序需要很多线程,数百个,theadpool有最大线程限制,休息任务排队。

我该如何管理?

更新:这是代码,如果有更好的代码,请告诉我。

public class ParallelV2
{
    static int waitcount = 0;
    static WaitHandle[] waitHandles;

    public static void Invoke(Action[] Actions)
    {
        waitcount = Actions.Length;

        Thread[] threadArray = new Thread[Actions.Length];
        waitHandles = new WaitHandle[Actions.Length];

        for (int i = 0; i < Actions.Length; i++)
        {
            var count = i;

            waitHandles[count] = new AutoResetEvent(false);
            threadArray[count] = new Thread(() =>
            {
                Actions[count].Invoke();
                ((AutoResetEvent)waitHandles[count]).Set();
            });

            threadArray[count].Start();
        }
    }

    public static void WaitAll()
    {
        while (waitcount > 0)
        {
            WaitHandle.WaitAny(waitHandles);
            waitcount--;
        }
    }

    public static void WaitAny()
    {
        WaitHandle.WaitAny(waitHandles);
    }
}

2 个答案:

答案 0 :(得分:4)

您可以等待帖子myThread完成myThread.Join()

答案 1 :(得分:4)

在下面的示例中,我需要跟踪三个线程。每个线程完成后都会设置相应的句柄。

声明如下:

private WaitHandle[] waithandles;  // see comment on static below

像这样创建:

waitcount = 3;
waithandles = new WaitHandle[3] { new AutoResetEvent(false), new AutoResetEvent(false), new AutoResetEvent(false) };

在线程中,完成后,将其设置为:

((AutoResetEvent)waithandles[i]).Set();

(实际上,那些过度简化了,但是如果你把waithandle设置为静态它会起作用。我实际上做的是让线程在其生命结束时执行回调来发出等待句柄的信号)

在主线程中,像这样检查一下。当waitcount达到零时,我知道所有线程都已完成

while (waitcount > 0)
{
    WaitHandle.WaitAny(waithandles, 30000);
    waitcount--;
}