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

前端 未结 4 2014
面向向阳花
面向向阳花 2020-11-29 06:27

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 (including the documentation).

4条回答
  •  -上瘾入骨i
    2020-11-29 07:10

    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.

提交回复
热议问题