我创建了一个简单的WPF应用程序,并在默认窗口中添加了一个按钮。当我单击该按钮时,会调用一个模拟的长时间工作方法(使用Thread.Sleep(15000)模拟)。我正在尝试使按钮异步执行,但是尽管遵循在线示例,但按钮和整个窗口在我单击后锁定,并且一直保持到Thread.Sleep(...)完成。
有什么想法为什么会发生这种情况吗?
以下是代码:
private void button1_Click(object sender, RoutedEventArgs e)
{
DoSomeAsyncWork();
}
private void DoSomeAsyncWork()
{
System.Windows.Threading.Dispatcher.Run();
Thread thread = new System.Threading.Thread(
new System.Threading.ThreadStart(
delegate()
{
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() => Thread.Sleep(15000)));
}
));
thread.Start();
}
Dispatcher.BeginInvoke(...short UI operation...)
。这会导致UI被多次短暂阻塞,而不是一次长时间阻塞。 - Heinzi