问题
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