How to Cancel a Thread?

前端 未结 4 2051
旧巷少年郎
旧巷少年郎 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 13:58

    Here is a full example of one way of doing it.

    private static bool _runThread;
    private static object _runThreadLock = new object();
    
    private static void Main(string[] args)
    {
        _runThread = true;
        Thread t = new Thread(() =>
        {
            Console.WriteLine("Starting thread...");
            bool _localRunThread = true;
            while (_localRunThread)
            {
                Console.WriteLine("Working...");
                Thread.Sleep(1000);
                lock (_runThreadLock)
                {
                    _localRunThread = _runThread;
                }
            }
            Console.WriteLine("Exiting thread...");
        });
        t.Start();
    
        // wait for any key press, and then exit the app
        Console.ReadKey();
    
        // tell the thread to stop
        lock (_runThreadLock)
        {
            _runThread = false;
        }
    
        // wait for the thread to finish
        t.Join();
    
        Console.WriteLine("All done.");    
    }
    

    In short; the thread checks a bool flag, and keeps runing as long as the flag is true. I prefer this approach over calling Thread.Abort becuase it seems a bit nicer and cleaner.

提交回复
热议问题