开发者

C# Loading screen / Threading issue

Before my main form loads it asks the user to check for 开发者_StackOverflow社区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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜