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

Posted by Lirik on Stack Overflow See other posts from Stack Overflow or by Lirik
Published on 2010-03-19T04:14:56Z Indexed on 2010/03/19 4:21 UTC
Read the original article Hit count: 199

My main concern is with the boolean flag... is it safe to use it without any synchronization? I've read in several places that it's atomic.

class MyTask
{
    private ManualResetEvent startSignal;
    private CountDownLatch latch;
    private bool running;

    MyTask(CountDownLatch latch)
    {
        running = false;
        this.latch = latch;
        startSignal = new ManualResetEvent(false);
    }

    // A method which runs in a thread
    public void Run()
    {
        startSignal.WaitOne();
        while(running)
        {
            startSignal.WaitOne();
            //... some code
        }
        latch.Signal();
    }

    public void Stop()
    {
        running = false;
        startSignal.Set();
    }

    public void Start()
    {
        running = true;
        startSignal.Set();
    }

    public void Pause()
    {
        startSignal.Reset();
    }

    public void Resume()
    {
        startSignal.Set();
    }
}

Is this a safe way to design a task? Any suggestions, improvements, comments?

Note: I wrote my custom CountDownLatch class in case you're wondering where I'm getting it from.

© Stack Overflow or respective owner

Related posts about c#

Related posts about multithreading