Arm0geddon
Arm0geddon

Reputation: 484

Multi-thread UI causing WPF application to stop working

A pop up window in my application needs to make all other windows modal, except for the one displaying a PDF document. After some searching, i found that if the PDF window is on another thread, a popup window will not disable it. However, when an exception is raised for any reason on the PDF window on the other thread, the user receives an "application has stopped working" and the whole application is closed by Windows. Even though the thread is in a try-catch block. Am I doing something wrong? Why is the exception causing Windows to shut down the application?

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();
    }
}

Upvotes: 1

Views: 395

Answers (1)

Peter Duniho
Peter Duniho

Reputation: 70701

As the commenter stijn points out, you are putting your try/catch in the wrong place. Do this instead:

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);
    }
}

Upvotes: 2

Related Questions