Can I cancel methods through delegates in C #

I would like to terminate the method immediately if I click "cancel" on the "processing" processing screen. I am using Async call through delegates. Is it possible to immediately terminate a method through delegates?

Thanks:)

+6
c # delegates
source share
3 answers

No - at least not clean. (I do not include Thread.Abort as “clean.”) What you should do is have a mechanism to tell the delegate that you are trying to cancel it. Then your delegate will sometimes have to check this cancel flag and react accordingly.

Parallel extensions have a cancellation built into it (and, in particular, cancellation tokens that allow only the corresponding code fragments to cancel the task). As far as I know, all this cooperation. Forced cancellation will always threaten corruption.

+9
source share

You can use System.ComponentModel.BackgroundWorker . It supports cancellation, so you do not need to write boilerplate code. The client code can simply call the CancelAsyn method, and you can check the CancellationPending in your code, when and where it makes sense to determine whether the client canceled the operation and helped out.

+5
source share

As John already said, you cannot say the thread: “please stop now” and expect the thread to obey. Thread.Abort will not say that it stops, it will simply "disable" it. :)

What I did in the past added a series of “if (wehavetostop)” inside the stream code, and if the user clicked “cancel”, I set wehavetostop == true.

This is not very elegant, and in some cases it can be “difficult” to put “if” checks, especially if your thread performs a “long” operation that you cannot split.

If you are trying to establish a network connection (and it takes time) and you really think that the “abnormal” termination of the stream will not cause any distorting state, you can use it, but remember that you cannot trust the state of things that were involved into this thread.

+1
source share

All Articles