How to cancel a topic?

In the case of BackgroundWorker cancellation can be reported using the e.Cancel property, the e.Cancel event handler.

How can I achieve the same with Thread object?

+4
source share
4 answers

Here is a complete example of one way to do this.

 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 the bool flag and continues to work as long as the flag is true . I prefer this approach to calling Thread.Abort , because it seems a little better and cleaner.

+7
source

Typically, you do this by executing a thread that is a delegate of the method on the object, with this object displaying the Cancel property, and a lengthy operation that passes this property periodically to tru to determine whether to exit.

eg

 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 in another place:

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

A locked thread can be stopped prematurely in one of two ways:

  • Thread.interrupt

  • Thread.Abort

The main question is whether the stream works for any ressources that need to be released correctly - in this case you need to work with the property on the actual object that starts the stream.

-one
source

Here's Thread.Abort , which works by inserting ThreadAbortException into the thread. This is a bit risky because:

  • Your thread may get stuck if it executes native code at that time
  • The code in the stream is better to be safe for exceptions, because this ThreadAbortException can occur in any line of code inside it, even in something innocent, for example i = i + 1

You better code your own signaling mechanism between your GUI thread and the background thread. It is hard to recommend something without knowing what is going on inside this thread, but where I have a thread that works, waiting for some kind of object in a loop, I use AutoResetEvent and wait for this too.

-one
source

All Articles