【发布时间】:2013-10-11 15:07:56
【问题描述】:
我为 WinForm 应用程序创建了启动画面。一切正常,直到初始屏幕只是一个带有背景图像和带有静态文本标签的表单 - “正在加载...”
我想用文本连续更新标签(中间有小延迟) - “加载”,“加载。”,“加载..”和“加载......”。为此,我将以下代码放入我的 SplashScreen 表单中:
private void SplashScreen_Load(object sender, EventArgs e)
{
lblLoading.Refresh();
lblLoading.Text = "Loading.";
Thread.Sleep(500);
lblLoading.Refresh();
lblLoading.Text = "Loading..";
Thread.Sleep(500);
lblLoading.Refresh();
lblLoading.Text = "Loading...";
Thread.Sleep(500);
}
现在启动画面不会出现,直到其中的标签更新为“正在加载...”
请帮助让我知道我做错了什么。
代码在我的HomeScreen:
public HomeScreen()
{
//....
this.Load += new EventHandler(HandleFormLoad);
this.splashScreen = new SplashScreen();
}
private void HandleFormLoad(object sender, EventArgs e)
{
this.Hide();
Thread thread = new Thread(new ThreadStart(this.ShowSplashScreen));
thread.Start();
//...Performing tasks to be done while splash screen is displayed
done = true;
this.Show();
}
private void ShowSplashScreen()
{
splashScreen.Show();
while (!done)
{
Application.DoEvents();
}
splashScreen.Close();
this.splashScreen.Dispose();
}
编辑:
正如一些用户在这里建议的那样,我已将启动任务放在后台线程中,现在我正在从主线程显示启动画面。但同样的问题仍然存在。这是HomeScreen表单的更新代码:
public HomeScreen()
{
//...
this.Load += new EventHandler(HandleFormLoad);
}
private void HandleFormLoad(object sender, EventArgs e)
{
this.Hide();
SplashScreen sc = new SplashScreen();
sc.Show();
Thread thread = new Thread(new ThreadStart(PerformStartupTasks));
thread.Start();
while (!done)
{
Application.DoEvents();
}
sc.Close();
sc.Dispose();
this.Show();
}
private void PerformStartupTasks()
{
//..perform tasks
done = true;
}
这是Splash Screen:
private void SplashScreen_Load(object sender, EventArgs e)
{
lblLoading.Update();
lblLoading.Text = "Loading.";
Thread.Sleep(500);
lblLoading.Update();
lblLoading.Text = "Loading..";
Thread.Sleep(500);
lblLoading.Update();
lblLoading.Text = "Loading...";
Thread.Sleep(500);
}
【问题讨论】:
-
你不要把它倒过来..启动画面需要在主线程中,加载需要在后台......看看是否有帮助。
-
你应该了解
ManualResetEvent。while(!done){}很苛刻... -
@logixologist 我尝试按照您的建议进行操作。仍然没有帮助。请看我的编辑
标签: c# .net multithreading winforms