1

I'm using a backgroundworker for showing a loadingscreen.

The DO-event looks as follow:

private void bwLoadingScreen_DoWork(object sender, DoWorkEventArgs e)
{
            _ls = new LoadingScreen();
            _ls.Show();
            while (!bwLoadingScreen.CancellationPending)
            {
                Application.DoEvents();
           }
}

I use the following code to Dispose the Loadingscreen:

if (_ls.InvokeRequired && !_ls.IsDisposed)
            {
                Invoke(new MethodInvoker(delegate
                    {
                        _ls.Close();
                        _ls.Dispose();
                    }));
            }
            else if (!_ls.IsDisposed)
            {
                _ls.Hide();
                _ls.Dispose();
            }

Should I use the RunWorkerCompleted event for this? Is this the right way to use the Backgroundworker?

Max
  • 11,136
  • 15
  • 65
  • 92

2 Answers2

4

I feel like you are doing this a bit backwards. Backgroundworker should do the work while your main process is displaying the current form and possibly updating it. When the backgroundworker has finished loading your data it should process it in the main thread in the backgroundworker event 'RunWorkerCompleted'.

This will also simplify your code since you do not need to your invokes before closing or hiding the form.

I hope this answered your question. //Flipbed

Flipbed
  • 690
  • 9
  • 17
2

Here is some great articles that may help you get what you want :

C# BackgroundWorker Tutorial

BackgroundWorker Class Sample for Beginners

BackgroundWorker and ProgressBar demo

Backgroundworker example

Hope this Helps!

Obama
  • 2,406
  • 2
  • 27
  • 47