Search code examples
c#multithreadingasynchronousthreadpoolwaithandle

WaitHandle fundamental behavior


Have those two code blocks the same effect when looking at the console?
Please note: Currently I am still using and bound to .NET 3.5.

First:

for(int i = 0; i<3;i++)
{
    Console.WriteLine(i);
}

Second:

class Worker
{
    static int i = 0;
    static ManualResetEvent manualResetEvent = new ManualResetEvent(false);       
    static Object locky = new Object();
    static void Work(Object workItem)
    {
        WaitHandle[] wait = new [] { manualResetEvent };

        while (WaitHandle.WaitAny(wait))
        {
            lock (locky)
            {
                Console.WriteLine(i++);
            }
        }
    }
}
// main:

Thread thread = new Thread(Worker.Work);
thread.Start();

for (int i=0;i<3;i++)
{
    Worker.manualResetEvent.Set();
}

Will the waitHandle increase with every signal? Will the loop run until all signals are done? Or will a signal be ignored when the thread is already working?

Can someone please bring some light into this?


Solution

  • Since you're using a ManualResetEvent, once you signal the event, it remains signaled until it's reset. Which means setting it once or three times will have the same effect.

    This also means that the worker will go into an infinite loop because the event is never reset.

    Also, you can't lock on value types. If you could, the int would be boxed and create a new object every time you lock on it - which means you'd be locking on a different object every single time, rendering the lock useless.