I have time-consuming function and I want to give the user an opportunity to stop it by clicking a button in the UI when he notices that it takes too long. How can I do this?
- msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspxJoe– Joe2012-08-27 18:02:23 +00:00Commented Aug 27, 2012 at 18:02
- 1You'll need to run it on a different thread, then provide some kind of signal or abort the thread.Ry-– Ry- ♦2012-08-27 18:02:54 +00:00Commented Aug 27, 2012 at 18:02
- Create a Task<T> and use Cancellation RequestAdil– Adil2012-08-27 18:05:27 +00:00Commented Aug 27, 2012 at 18:05
5 Answers
You can use BackgroundWorker class to run time and resource consuming stuff on other thread, and use its CancelAsync method, to request (it's not immediate execution) cancelation of the other thread.
For concrete example on how to implement that, can have a look on accepted answer in this question:
Comments
First of all, you need to run the time-consuming function in a thread separate from the main thread. Otherwise the UI will stop responding.
Then you need to have a static variable or a shared instance where the UI can set a flag indicating that the time-consuming function should stop.
Finally, the time-consuming function should regular check the flag and stop processing if it is set.
The BackgroundWorker class implements this pattern and solves a few other requirements as well (such as the inter-thread communication and the progress reporting).
Comments
Try running it on a Background Worker.
This Gives a good example of how to use it.
Then you can call
Worker.CancelAsync(); when the user wants to cancel the operation
Comments
Here's an example
bool _cancel = false; private void count() { _cancel = false; new System.Threading.Thread(delegate() { for (int i = 0; i < 100000; i++) { if (_cancel) break; Console.WriteLine(i); } }).Start(); } private void button1_Click(object sender, EventArgs e) { _cancel = true; } 10 Comments
_cancel will need to be marked volatile, or wrapped in a lock block, to ensure the proper memory barriers are added.