0

在我的主表单加载之前,它会要求用户检查更新。当他们单击确定时,我会显示主窗体并制作一个包含一些标签和一个带有动画 gif 的图片框的面板。

动画 gif 没有移动,这通常是因为主线程很忙,但我已经线程化了线程来完成工作并且没有运气让动画播放。

这就是我所拥有的。

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;
4

2 回答 2

3

问题是 Thread.Join() 将阻塞调用线程,直到您等待的线程完成。

相反,您应该对此类活动使用异步模型。BackgroundWorker 在这里是理想的:

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

这只是一个粗略的实现示例,但与我过去所做的许多类似。

于 2011-10-12T15:30:26.723 回答
2

CheckVersion.Join() 调用使您的 UI 线程等待 CheckVersion 线程完成,这会阻塞。这使 GIF 动画暂停。

尝试使用BackgroundWorker类,并使用该RunWorkerCompleted事件向您的 UI 线程发出后台操作已完成的信号。

于 2011-10-12T15:21:25.273 回答