我的应用程序中的弹出窗口需要使所有其他窗口模态,除了显示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();
}
}
答案 0 :(得分:2)
正如评论者指出的那样,你将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);
}
}