我的应用程序有一个UserControl,它包装ServiceController以向用户公开启动/停止/重启win服务功能。我现在关心的是重新启动。这需要花费很少的时间,我想反映控件内部的重启状态。这大致与重启按钮单击处理程序
相同private void RestartButton_Click(object sender, RoutedEventArgs e)
{
startStopButton.Visibility = Visibility.Hidden;
restartButton.Visibility = Visibility.Hidden;
statusTextBlock.Text = "Restarting...";
Controller.Stop();
Controller.WaitForStatus(ServiceControllerStatus.Stopped);
Controller.Start();
Controller.WaitForStatus(ServiceControllerStatus.Running);
startStopButton.Visibility = Visibility.Visible;
restartButton.Visibility = Visibility.Visible;
statusTextBlock.Text = Controller.Status.ToString();
}
即使我单步执行调试器,我也看不到应用程序中反映的这些更改。一定是我缺少的东西。此外,我已经尝试禁用按钮而不是隐藏它们,这也不起作用。
答案 0 :(得分:2)
您正在UI线程上执行所有操作,因此在此代码完成之前不会更新UI。你应该在后台线程上进行繁重的工作。 BackgroundWorker
组件使这很容易:
private void RestartButton_Click(object sender, RoutedEventArgs e)
{
startStopButton.Visibility = Visibility.Hidden;
restartButton.Visibility = Visibility.Hidden;
statusTextBlock.Text = "Restarting...";
var backgroundWorker = new BackgroundWorker();
// this delegate will run on a background thread
backgroundWorker.DoWork += delegate
{
Controller.Stop();
Controller.WaitForStatus(ServiceControllerStatus.Stopped);
Controller.Start();
Controller.WaitForStatus(ServiceControllerStatus.Running);
};
// this delegate will run on the UI thread once the work is complete
backgroundWorker.RunWorkerCompleted += delegate
{
startStopButton.Visibility = Visibility.Visible;
restartButton.Visibility = Visibility.Visible;
statusTextBlock.Text = Controller.Status.ToString();
};
backgroundWorker.RunWorkerAsync();
}
答案 1 :(得分:0)
那是因为执行发生在UI线程中。您的按钮不会更新,因为在{
和}
之间,UI线程忙于完成您的工作而无法更新按钮。