开发者

Dispose of dialogwindow in backgroundworker

开发者 https://www.devze.com 2023-04-12 12:51 出处:网络
i\'m loading screen in backgroundworker: private void LSLoadingScreen(object sender, DoWorkEventArgs e)

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..

  1. Fire background worker (which does loading code)
  2. Show your loading dialog
  3. 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();
   }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号