为此使用async。
private async void BtnInstall_Click(object sender,RoutedEventArgs e)
{
this.lblResponse.Content = "";
await Task.Run(()=> executeInstall());
this.lblResponse.Content = "DONE";
}
更新:如果您需要在executeIntall
方法内访问UI,则需要调用Dispatcher。在这种情况下,您需要延迟Task来给标签时间在安装开始之前进行更新。请注意,这将导致UI在整个安装过程中冻结。
private async void BtnInstall_Click(object sender,RoutedEventArgs e)
{
lblResponse.Content = "starting...";
await Task.Delay(100).ContinueWith(_=>
{
App.Current.Dispatcher.Invoke(() =>
{
executeInstall();
lblResponse.Content = "DONE";
});
});
}
更好的方法是仅在实际需要时才调用调度程序。这将使UI在整个过程中保持响应。
private async void BtnInstall_Click(object sender,RoutedEventArgs e)
{
lblResponse.Content = "starting...";
await Task.Run(()=> executeInstall());
lblResponse.Content = "DONE";
}
private void executeInstall()
{
Thread.Sleep(1000); //do time consuming operation
App.Current.Dispatcher.Invoke(() => lblResponse.Content = "Downloading Files...");
Thread.Sleep(1000); //do time consuming operation
App.Current.Dispatcher.Invoke(() => lblResponse.Content = "Unzipping Files...");
Thread.Sleep(1000); //do time consuming operation
App.Current.Dispatcher.Invoke(() => lblResponse.Content = "Updating Files...");
Thread.Sleep(1000); //do time consuming operation
}
本文链接:https://www.f2er.com/3106207.html