【发布时间】:2020-04-14 08:01:59
【问题描述】:
我目前正在尝试实现启动画面。我以this tutorial 为起点。
我的 App.xaml.cs 中的 OnStartup 如下所示:
protected override void OnStartup(StartupEventArgs e)
{
//initialize the splash screen and set it as the application main window
splashScreen = new MySplashScreen();
this.MainWindow = splashScreen;
splashScreen.Show();
//in order to ensure the UI stays responsive, we need to
//do the work on a different thread
Task.Factory.StartNew(() =>
{
//we need to do the work in batches so that we can report progress
for (int i = 1; i <= 100; i++)
{
//simulate a part of work being done
System.Threading.Thread.Sleep(30);
//because we're not on the UI thread, we need to use the Dispatcher
//associated with the splash screen to update the progress bar
splashScreen.Dispatcher.Invoke(() => splashScreen.Progress = i);
splashScreen.Dispatcher.Invoke(() => splashScreen.MyText = i.ToString());
}
//once we're done we need to use the Dispatcher
//to create and show the main window
this.Dispatcher.Invoke(() =>
{
//initialize the main window, set it as the application main window
//and close the splash screen
var mainWindow = new MainWindow();
this.MainWindow = mainWindow;
mainWindow.Show();
splashScreen.Close();
});
});
}
这非常有效。启动画面被调用,进度(ProgressBar)增加到 100。
现在我不仅要从 OnStartup 中写入进度到启动屏幕,还要从 MainWindow 的构造函数中写入进度。
我的 MainWindow 构造函数:
public MainWindow()
{
InitializeComponent();
((App)Application.Current).splashScreen.Dispatcher.Invoke(() => ((App)Application.Current).splashScreen.MyText = "From MainWindow");
// do some stuff that takes a few seconds...
}
这没有按预期工作。只有在完全调用构造函数后,才会在初始屏幕的文本框中更新文本“From MainWindow”。在执行“做一些需要几秒钟的事情......”之前并不像预期的那样。
我的错误是什么?这是否和我想的一样?
【问题讨论】:
标签: c# wpf multithreading user-interface