单击在第二个线程上创建的WPF窗口会导致它停止响应

本文关键字:响应 窗口 WPF 第二个 线程 创建 单击 | 更新日期: 2023-09-27 18:28:13

在我当前的项目中,我正在第二个线程中创建一个基于WPF的进度窗口。请参阅我以前的帖子,了解我如何做到这一点的详细信息。

我在第二个线程上打开进度窗口的委托方法如下:

void ShowProgressWindow()
{
    this.progressWindow = new ProgressWindow();
    progressWindow.Show();
    //Causes dispatcher to shutdown when window is closed
    progressWindow.Closed += (s, e) => Dispatcher.CurrentDispatcher.BeginInvokeShutdown(DispatcherPriority.Background);
    //Notifies other thread the progress window is open when the dispatcher starts up
    System.Windows.Threading.Dispatcher.CurrentDispatcher.BeginInvoke(new Func<bool>(_progressWindowWaitHandle.Set));
    //Starts the dispatcher
    System.Windows.Threading.Dispatcher.Run();

    //Forces the worker to cancel work
    workerInstance.RequestCancel();
}

因此,如果用户在进程仍在运行时关闭窗口,调度程序将关闭,代码将从dispatcher.Run()继续到下一行,在那里工作将被取消。之后进度窗口线程将退出。

如果通过单击窗口右上角的X来关闭窗口,则此操作效果良好。窗口立即关闭,工作被取消。

然而,如果我单击添加到窗口中的取消按钮,进度窗口不会关闭,并且完全停止响应。我的取消按钮有一个非常简单的点击事件处理程序,它只需在窗口上调用Close()。

private void cancelButton_Click(object sender, RoutedEventArgs e)
{
    this.Close();
}

如果我在这个方法中设置了一个断点,那么在我单击按钮后,它永远不会被击中。

我的按钮的XAML是相当标准的

<Button x:Name="cancelButton"  Content="Cancel" Grid.Row="7" HorizontalAlignment="Right" Grid.Column="1" Margin="0,0,12,12" Width="75" Height="23" VerticalAlignment="Bottom" Click="cancelButton_Click" />

在处理了更多之后,我意识到在窗口中的任何位置点击,而不仅仅是取消按钮,都会导致它停止响应。当窗口第一次打开时,我可以通过抓住标题栏在屏幕上拖动它,但如果我单击窗口内的任何位置,它都会冻结。

单击在第二个线程上创建的WPF窗口会导致它停止响应

有几种方法可以在UI线程上运行一些代码。。。我更喜欢这种方式:

Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Normal, (Action)delegate()
{
    // Open window here
});