Is there any reason to use WaitHandle over bool to mark for undo?

I inherited a bit of streaming code, and looking at it, I find structures like this (in the background thread method):

private ManualResetEvent stopEvent = new ManualResetEvent(false);

private void Run_Thread() {
    while (!stopEvent.WaitOne(0, true)) {
        // code here
    }
}

There is usually a public or private method Stop(), for example:

public void Stop() {
    stopEvent.Set();
    bgThread.Join();
}

My question is: what is served using the wait descriptor here? It seems that this is done so that the alarm for stopping is an atomic operation, but I thought that writing to the logical value of the atom anyway. If so, is there a reason to not just use the following:

private void Run_Thread() {
    while(!stop) {
        // code here
    }
}

public void Stop() { 
    stop = true;
    bgThread.Join();
}
+3
source share
3 answers

bool , ( - ), . .

, x64 . x86 . ( csc /o+ Test.cs).

using System;
using System.Threading;

class Test
{
    static bool stop = false;

    static void Main(string[] args)
    {
        new Thread(CountLots).Start();
        Thread.Sleep(100);
        stop = true;
        Console.WriteLine("Finished...");
    }    

    static void CountLots()
    {
        long total = 0;
        while (!stop)
        {
            total++;
        }
    }
}

volatile - , .NET 4, :)

, - , , - - " " " " ( ) .

+7

/ "" bool ( , , , Monitor ).

bool , bool volatile .

+1

Just using bool will not work, you have to declare it volatile to tell the code generator that it should not store the value in the CPU register. The exact time when the thread sees the value set to true is unpredictable, it depends heavily on the type of processor your code is running on.

Horrible details that you can ignore when using WaitHandle.

The final argument should be False btw.

+1
source

All Articles