Dispose of dialogwindow in backgroundworker
i'm loading screen in backgroundworker:
private void LSLoadingScreen(object sender, DoWorkEventArgs e)
{
LoadingScreen ls = new LoadingScreen(this.timerStart);
ls.ShowDialog();
while (LoadingScreen.CancellationPending)
{
ls.Dispose();
LoadingScreen.Dispose();
开发者_JAVA百科 }
but my loadingScreen doesn't dispose when i use this code in other function:
LoadingScreen.CancelAsync();
timerStart = false;
LoadingScreen.Dispose();
How to dispose it properly?
Firstly, ShowDialog() will prevent the rest of the code executing until the dialog is closed - which you are never doing.
Even when it does close, it will evaluate the while loop (which will most likely be false so skipped) and then your backgroundworker will be finished.
If all you are doing is showing a dialog then I would just do this on the main thread, and have your loading process on the background worker..
- Fire background worker (which does loading code)
- Show your loading dialog
- On BackgroundWorkerCompleted event, close your loading dialog
Try to get all your UI elements in the main UI thread.
Hope that helps
EDIT:
Based on your comment...
public partial class MainForm:Form
{
LoadingScreen ls;
public MainForm()
{
}
public void StartLoad()
{
ls = new LoadingScreen(this.timerStart);
backgroundWorker.RunWorkerAsync();
ls.Show();
}
void backgroundWorkerDoWork(object sender, DoWorkEventArgs e)
{
//Loading code goes here
}
void BackgroundWorkerMainRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if(ls != null)
ls.Close();
}
}
精彩评论