views:

1591

answers:

4

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

A: 

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);
}
jons911
+1  A: 

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'.

Enrico Campidoglio
A: 

You haven't misunderstood - using ReportProgress or using a delegate (as I do) achieve essentially the same goal.

eft
A: 

Your ui code can display the animation before it starts the background worker, And if need be to cancel, you can terminate the background thread. You will not unfortunately beable to utilize the background worker design.

Aaron Fischer