How do I "Thread.Join" create a BackgroundWorker?

Let's say I show the user a form and use BackgroundWorker to do some work behind the scenes.

When the user clicks β€œOK,” I cannot continue until BackgroundWorker completes. If he has not finished when the user clicks β€œOK”, I want to show WaitCursor before it appears, and then continue.

What is the best way to implement this?

I know I can use the plain old Thread and then Thread.Join, but I like BackgroundWorker.

Can this be done beautifully?

+4
source share
4 answers

You can 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 
+8
source

Ideally, you should turn off all relevant controls on the form, and then turn them back on when BackgroundWorker completes. This way you won’t get a blocked user interface - and you may have a cancel button, etc.

If you want to block a block before it is completed, you can simply run the task synchronously to start with.

+8
source

You can check if BackgroundWorker works with validation in the btnOK_Click event handler to see if bw.IsBusy is true. If so, change the cursor and set the boolean flag, which indicates that the OK handler is waiting. When BackgroundWorker completes the test, if ok expected, if so, set the flag to false, change the cursor and set the OK button. :-)

+2
source

I would just use boolean flags and locks.

 object waitlock = new object(); bool isBackgroundWorkerCompleted = false; bool isOKButtonPressed = false; private void onPress(...) { lock(waitlock) { isOKButtonPressed = true; if (isBackgroundWorkerCompleted) DoNextStep(); else cursor.Wait(); //psuedo-code - use whatever the actual call is... } } 

The background thread does the same trick (just remember BeginInvoke back to the main UI thread)

0
source

Source: https://habr.com/ru/post/1286733/


All Articles