如何取消线程?

use*_*312 6 c# multithreading

在这种情况下BackgroundWorker,可以通过- 事件处理程序的e.Cancel- 属性报告取消DoWork.

如何用Thread对象实现相同的功能?

Fre*_*örk 9

以下是一种完成此方法的示例.

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.");    
}
Run Code Online (Sandbox Code Playgroud)

简而言之; 线程检查bool标志,并且只要该标志持续运行true.我更喜欢这种方法,Thread.Abort因为它似乎更好,更清洁.


Jam*_*iec 6

通常,您通过线程的执行作为对象上的方法的委托来执行此操作,该对象公开Cancel属性,并且长时间运行的操作定期为tru确定是否退出该属性.

例如

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
     }
   }
}
Run Code Online (Sandbox Code Playgroud)

其他地方:

var longRunning = new MyLongTunningTask();
Thread myThread = new Thread(new ThreadStart(longRunning.ExecuteLongRunningTask));

myThread.Start();

// somewhere else
longRunning.Cancel = true;
Run Code Online (Sandbox Code Playgroud)

  • 您需要在Cancel成员上放置volatile以指示它将从另一个线程更改. (3认同)