How to terminate a worker thread correctly in c#

后端 未结 4 1672
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-15 23:36

Problem statement

I have a worker thread that basically scans a folder, going into the files within it, and then sleeps for a while. The scanning operat

4条回答
  •  后悔当初
    2021-02-16 00:25

    I recommend to keep it simple:

    while (m_shouldRun)
    {
        DoSomethingThatTakesSeveralSeconds();
        for (int i = 0; i < 5; i++)  // example: 5 seconds sleep
        {
            if (!m_shouldRun)
                break;
            Thread.Sleep(1000);
        }
    }
    
    public void Stop()
    {
        m_shouldRun = false;
        // maybe thread.Join();
    }
    

    This has the following advantages:

    • It smells like busy waiting, but it's not. $NUMBER_OF_SECONDS checks are done during the waiting phase, which is not comparable to the thousands of checks done in real busy waiting.
    • It's simple, which greatly reduces the risk of error in multi-threaded code. All your Stop method needs to do is to set m_shouldRun to false and (maybe) call Thread.Join (if it is necessary for the thread to finish before Stop is left). No synchronization primitives are needed (except for marking m_shouldRun as volatile).

提交回复
热议问题