首页 文章

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

提问于
浏览
1

在我当前的项目中,我正在第二个线程中创建一个基于WPF的进度窗口 . 有关我如何执行此操作的详细信息,请参阅我的previous post .

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

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" />

在搞砸了这个之后,我意识到点击窗口中的任何地方,而不仅仅是取消按钮,都会导致它停止响应 . 当窗口第一次打开时,我可以通过 grab Headers 栏将其拖动到屏幕上,但是如果我点击窗口内的任何位置它将会冻结 .

1 回答

  • 0

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

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

相关问题