繁体   English   中英

多线程UI导致WPF应用程序停止工作

[英]Multi-thread UI causing WPF application to stop working

我的应用程序中的一个弹出窗口需要使所有其他窗口变为模态,除了显示PDF文档的窗口。 经过一番搜索,我发现如果PDF窗口在另一个线程上,则弹出窗口不会禁用它。 但是,当由于其他原因在另一个线程的PDF窗口上引发异常时,用户会收到“应用程序已停止工作”,并且整个应用程序被Windows关闭。 即使线程在try-catch块中。 难道我做错了什么? 为什么异常导致Windows关闭应用程序?

public static void OpenPdfDocument(string pdfPath)
{
    try
    {
        Thread pdfDocuThread = new Thread(new ParameterizedThreadStart(OpenPdfHelper));
        pdfDocuThread.SetApartmentState(ApartmentState.STA);
        pdfDocuThread.IsBackground = true;
        pdfDocuThread.Start(pdfPath);
    }
    catch (Exception ex)
    {
        Mouse.OverrideCursor = null;
        AppErrorLog.LogError("PDFTHREADERROR: " + ex.Message);
    }
}

private static void OpenPdfHelper(object pdfPath)
{
    if (pdfPath is string)
    {
        DisplayPdfWindow pdfViewer = new DisplayPdfWindow();
        pdfViewer.Loaded += (s, ev) => { pdfViewer.SetPdf(pdfPath.ToString()); };
        pdfViewer.Closed += (s, ev) => { pdfViewer.Dispatcher.InvokeShutdown(); };
        pdfViewer.Show();
        Dispatcher.Run();
    }
}

正如评论者stijn指出的那样,您将try/catch放在错误的位置。 改为这样做:

public static void OpenPdfDocument(string pdfPath)
{
    Thread pdfDocuThread = new Thread(
        new ParameterizedThreadStart(OpenPdfHelper));
    pdfDocuThread.SetApartmentState(ApartmentState.STA);
    pdfDocuThread.IsBackground = true;
    pdfDocuThread.Start(pdfPath);
}

private static void OpenPdfHelper(object pdfPath)
{
    try
    {
        if (pdfPath is string)
        {
            DisplayPdfWindow pdfViewer = new DisplayPdfWindow();
            pdfViewer.Loaded += (s, ev) => { pdfViewer.SetPdf(pdfPath.ToString()); };
            pdfViewer.Closed += (s, ev) => { pdfViewer.Dispatcher.InvokeShutdown(); };
            pdfViewer.Show();
            Dispatcher.Run();
        }
    }
    catch (Exception ex)
    {
        Mouse.OverrideCursor = null;
        AppErrorLog.LogError("PDFTHREADERROR: " + ex.Message);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM