tags:

views:

394

answers:

3

I'd like to stop immediately a method if I press cancel in the "processing" animation screen. I'm using Async call through delegates. Is it possible to stop immediately the execution of the method through delegates?

Thanks :)

+6  A: 

No - at least, not cleanly. (I don't include Thread.Abort as "clean".) What you should do is have a mechanism to tell the delegate that you're trying to cancel it. Your delegate would then need to occasionally check that cancellation flag and react accordingly.

Parallel Extensions has cancellation built into it all over the place (and in particular cancellation tokens to allow only appropriate pieces of code to cancel the task). It's all still co-operative though, as far as I'm aware. Forced cancellation will always run the risk of corrupting state.

Jon Skeet
+1  A: 

As Jon has already stated, you can't tell a thread: "please stop now" and expect the thread to obey. Thread.Abort will not tell it to stop, will simply "unplug" it. :)

What I did in the past was add a series of "if (wehavetostop)" within the thread's code and if the user pressed a "cancel" I put wehavetostop == true.

It's not too elegant and in some cases it may be "hard" to put the "if" checks, specially if your thread runs a "long" operation that you can't divide.

If you are trying to establish a network connection (and it's taking time) and you really think that an "abnormal" termination of the thread wouldn't cause any corrupting state, you may use it, but remember that you cannot trust the state of things that were involved in that thread.

Martín Marconcini
+3  A: 

You can use System.ComponentModel.BackgroundWorker. It supports cancellation so that you don't have to write the boilerplate code. Client code can simply call CancelAsyn method and you can check CancellationPending property within your code when and where it makes sense to determine if the client has cancelled the operation and bail out.

Mehmet Aras