Do I need to lock or mark as volatile when accessing a simple boolean flag in C#?

前端 未结 5 1596
余生分开走
余生分开走 2020-11-28 23:38

Lets just say you have a simple operation that runs on a background thread. You want to provide a way to cancel this operation so you create a boolean flag that you set to t

5条回答
  •  [愿得一人]
    2020-11-29 00:01

    For thread synchronization, it's recommended that you use one of the EventWaitHandle classes, such as ManualResetEvent. While it's marginally simpler to employ a simple boolean flag as you do here (and yes, you'd want to mark it as volatile), IMO it's better to get into the practice of using the threading tools. For your purposes, you'd do something like this...

    private System.Threading.ManualResetEvent threadStop;
    
    void StartThread()
    {
        // do your setup
    
        // instantiate it unset
        threadStop = new System.Threading.ManualResetEvent(false); 
    
        // start the thread
    }
    

    In your thread..

    while(!threadStop.WaitOne(0) && !operationComplete)
    {
        // work
    }
    

    Then in the GUI to cancel...

    threadStop.Set();
    

提交回复
热议问题