Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread WaitHandle on a Single Thread

My code is

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

}

I want to wait for all threads to complete, and also get notification when any thread completes,

like WaitAny, WaitAll

But waithandles can be used on threadpools only, could not find any examples for use on single thread.

My app requires a lot of threads, hundreds of them, theadpool has max thread limit, rest tasks are queued.

How do I manage that??

UPDATE: here is the code, please let me know if better code possible.

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);
    }
}
like image 947
Milan Solanki Avatar asked Feb 23 '23 13:02

Milan Solanki


2 Answers

In the example below, I had three threads that I needed to track. Each thread, when it was done would set its corresponding handle.

Declare it like this:

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

Create it like this:

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

In the thread, when its finished,set it like this:

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

(Actually, thats over-simplified, but it will work if you make the waithandle static. What I actually did was have the thread perform a callback at the end of its life to signal the waithandle)

In the main thread, check it like this. When the waitcount reached zero, I knew all threads had completed

while (waitcount > 0)
{
    WaitHandle.WaitAny(waithandles, 30000);
    waitcount--;
}
like image 136
edepperson Avatar answered Mar 07 '23 16:03

edepperson


You can wait for a thread myThread to complete with myThread.Join().

like image 22
MRAB Avatar answered Mar 07 '23 17:03

MRAB