Can I cancel methods through delegates in C#

2019-06-18 05:28发布

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 :)

标签: c# delegates
3条回答
女痞
2楼-- · 2019-06-18 05:56

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.

查看更多
来,给爷笑一个
3楼-- · 2019-06-18 06:07

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.

查看更多
\"骚年 ilove
4楼-- · 2019-06-18 06:16

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.

查看更多
登录 后发表回答