How to Cancel a Thread?

前端 未结 4 2052
旧巷少年郎
旧巷少年郎 2020-12-06 13:18

In case of BackgroundWorker, a cancel can be reported by the e.Cancel - property of the DoWork - event handler.

How can I achieve the same

4条回答
  •  悲哀的现实
    2020-12-06 14:19

    Generally you do it by the thread's execute being a delegate to a method on an object, with that object exposing a Cancel property, and the long-running operation periodically chercking that property for tru to determine whether to exit.

    for example

    public class MyLongTunningTask
    {
       public MyLongRunninTask() {}
       public volatile bool Cancel {get; set; }
    
       public void ExecuteLongRunningTask()
       {
         while(!this.Cancel)
         {
             // Do something long running.
            // you may still like to check Cancel periodically and exit gracefully if its true
         }
       }
    }
    

    Then elsewhere:

    var longRunning = new MyLongTunningTask();
    Thread myThread = new Thread(new ThreadStart(longRunning.ExecuteLongRunningTask));
    
    myThread.Start();
    
    // somewhere else
    longRunning.Cancel = true;
    

提交回复
热议问题