Question

I'm trying to have a background worker running with a spinner running in the main thread and I would like to wait until the background worker is finished. Currently I can have one or the other. I have tried using a Auto Reset Event but that locks out the main thread therefore not displaying the spinner. Is there something similar to Auto Reset Event that does not lock out the main UI.

Here is some of my code

BackgroundWorker _bWorker = new BackgroundWorker();
_bWorker.DoWork += _bWorker_DoWork ;
_bWorker.RunWorkerCompleted += _bWorker_RunWorkerCompleted;

AutoResetEvent are = new AutoResetEvent(false);

_bWorker.RunWorkerAsync();

// Wait here until the background worker is finished
are.WaitOne();

...

private void _bWorker_DoWork(object sender, DoWorkEventArgs e)
{
    // Show spinner
    WaitSpinnerAdornerText = "Working";
    IsWaitSpinnerVisible = true;

    ...

    are.Set();
}


private void _bWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    IsWaitSpinnerVisible = false;
    ...
}

Any ideas? Any help is welcome! Thanks in advance.

Was it helpful?

Solution

The whole point of using a BackgroundWorker is that you don't 'wait' for it to complete. Just remove the AutoResetEvent and trigger any logic that currently resides after the RunWorkerAsync in the _RunWorkerCompleted.

Alternatively you could look into using the Task Parallel Library and have that code run as a continuation.

Lastly you could look into using the Async CTP for .net 4.0 in which the async/await features behave nearly identically to how you want to write the code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top