Right way of using Backgroundworker

雨燕双飞 提交于 2019-12-12 10:17:59

问题


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?


回答1:


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




回答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!



来源:https://stackoverflow.com/questions/16521680/right-way-of-using-backgroundworker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!