简体   繁体   中英

C# Loading screen / Threading issue

Before my main form loads it asks the user to check for updates. When they click ok i make the main form show and make a panel that contains some labels and a picture box with an animated gif.

The animated gif is not moving which normally is because the main thread is busy but I have threaded the thread doing the work and no luck getting the animation to play.

Here is what I have.

Thread CheckVersion = new Thread(new ThreadStart(VersionCheck));
this.Show(); //bring up the main form
this.BringToFront();
pCheckingVersions.Visible = true; //this contains the animated gif
Application.DoEvents(); //refresh ui so my box
CheckVersion.Start(); //start thread
CheckVersion.Join(); //wait for thread to exit before moving on
pDownloading.Visible = false;

The problem is that Thread.Join() is going to block the calling thread until the thread you are waiting on completes.

Instead you should use an asynchronous model for this kind of activity. A BackgroundWorker would be ideal here:

class MyForm
{
  private BackgroundWorker _backgroundWorker;

  public Myform()
  {
    _backgroundWorker = new BackgroundWorker();
    _backgroundWorker.DoWork += CheckVersion;
    _backgroundWorker.RunWorkerCompleted += CheckVersionCompleted;

    // Show animation
    // Start the background work
    _backgroundWorker.DoWork();
  }

  private void CheckVersion()
  {
    // do background work here
  }

  private CheckVersionCompleted(object sender, RunWorkerCompletedEventArgs e)
  {
    // hide animation
    // do stuff that should happen when the background work is done
  }
}

This is just a rough example of an implementation, but similar to many I have done in the past.

The CheckVersion.Join() call is making your UI thread wait for the CheckVersion thread to complete, which blocks. That makes the GIF animation pause.

Try using the BackgroundWorker class, and use the RunWorkerCompleted event to signal to your UI thread that the background operation is done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM