Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I "Thread.Join" a BackgroundWorker?

Say I'm showing the user a form, and using a BackgroundWorker to do some work behind the scenes.

When the user clicks OK, I cannot continue until the BackgroundWorker has completed. If it hasn't finished when the user clicks Ok, I want to show a WaitCursor until it has, and then continue.

What's the best way to implement this?

I know I could use a plain old Thread, and then do Thread.Join, but I like BackgroundWorker.

Can it be done nicely?

like image 367
Blorgbeard Avatar asked Dec 02 '22 07:12

Blorgbeard


1 Answers

You could use this code, instead of BW

var resetEvent = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(state =>
                {
                    Thread.Sleep(5000);//LongRunning task, async call
                    resetEvent.Set();
                });
resetEvent.WaitOne();// blocking call, when user clicks OK 
like image 180
Sergey Mirvoda Avatar answered Dec 04 '22 20:12

Sergey Mirvoda