I have a method processData() that takes a large amount of data and does some work on it. There's a start button that initiates the processing. I need a cancel button that stops the processing wherever it's at. How can I implement something like that? The thing I don't get is how to make the cancel button usable once the processing has started since the rest of the UI is frozen when the function is running.
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
Use a
BackgroundWorker
.Put the heavy code in the
DoWork
event.The cancel button should call
CancelAsync
on theBackgroundWorker
.In the heacy code in
DoWork
check theCancellationPending
property periodically. If the property istrue
you should abort the work.BackgroundWorker.CancelAsync Method is what you need. Here is a good example for you.
If you have got a time consuming process you will have to use a separate thread to handle that in order to support for cancellation. If you execute that time consuming process in the main thread(UI thread) it will be busy and won't take your cancellation request in to account until it finish that task. That's why you experience UI freezing.
If you use a backgroundWorker for your time consuming task and if you check the CancellationPending flag in the BackgroundWorker.DoWork method you could achieve what you want.
If you mean that the process should stop immediately and not even wait for a moment where it checks a cancellation token, you may consider running the process in a separate AppDomain and kill it when you cancel.
Although this is perfectly possible, I would recommend a controlled termination as in the other answers, especially when your process changes external state.