Is it safe to use a boolean flag to stop a thread from running in C#

You better mark it volatile though:

The volatile keyword indicates that a
field might be modified by multiple
concurrently executing threads. Fields
that are declared volatile are not
subject to compiler optimizations that
assume access by a single thread. This
ensures that the most up-to-date value
is present in the field at all times.

But I would change your loop:

    startSignal.WaitOne();
    while(running)
    {
        //... some code
        startSignal.WaitOne();
    }

As it is in your post the ‘some code’ might execute when the thread is stopped (ie. when Stop is called) which is unexpected and may be even incorrect.

Leave a Comment