Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BackgroundWorker thread : updating UI and aborting operation

Tags:

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

like image 430
eft Avatar asked Nov 11 '08 22:11

eft


2 Answers

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);
}
like image 141
jons911 Avatar answered Sep 18 '22 19:09

jons911


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

like image 44
Enrico Campidoglio Avatar answered Sep 21 '22 19:09

Enrico Campidoglio