I run a series of time consuming operations on a background worker thread. At various stages I update a (windows form) progress bar by invoking a delegate. However, one of the more time operations occurs on a single line of code.
Is it possible to :
a) Update the UI while that single line of code is being executed, or at least display an animated icon that shows the user that work is being done.
b) Let the user cancel the background worker thread while that single line of code is being executed
Unfortunately, probably not. The background worker thread needs to call ReportProgress to update the UI thread, and it needs to watch the CancellationPending to know whether it should stop or not. So, if your worker thread is running along-running operation in a single line, there's no way to make this work.
Perhaps, I've misunderstood, so here's code that simulates what I'm getting at:
public void DoWork() {
System.Threading.Thread.Sleep(10000);
// won't execute until the sleep is over
bgWorker.ReportProgress(100);
}
a) You could display an animated GIF on your form instead of a progress bar by using a PictureBox control. You can find detailed information on how to do that in this blog post.
b) The BackgroundWorker class has a CancelAsync method that will submit a request to cancel the current operation.
This will set the CancellationPending property of the BackgroundWorker to 'True'. In your DoWork event handler then, you will have to poll this property regularly in order to take the appropariate actions when its value changes.
Also note that for this to work, you will have to set the WorkerSupportsCancellation property of the BackgroundWorker to 'True'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With