내 WinForms 앱이 처리되지 않은 모든 예외를 처리하기 위해 Application.ThreadException 이벤트 처리기를 설치합니다. 처리기가 대화 상자를 표시합니다 (오류 발생, 버그 보고서 보내기 등).Application.ThreadException이 호출되지 않았습니다.
문제는 응용 프로그램이 모달 대화 상자를 표시 할 때 내 이벤트 핸들러가 호출되지 않는다는 것입니다. MessageBox 또는 예외 대화 상자를 표시하면 모든 예외가 자동으로 삼킨 것입니다. 그들을 붙잡을 방법이 있습니까?
다음은이 동작을 시뮬레이트하는 샘플 WinForms 응용 프로그램입니다. 이 응용 프로그램은 메시지 박스가 표시되면, 백그라운드에서 발생하는 모든 예외는 (ThreadException 핸들러가 호출되지 않습니다) 손실 :
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
class Program
{
static void Main()
{
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
var form = new MyForm();
Application.ThreadException += (s, e) =>
{
form.AppendText("ThreadException event handler is called.");
MessageBox.Show("Error: " + e.Exception);
};
Application.EnableVisualStyles();
Application.Run(form);
}
}
class MyForm : Form
{
public MyForm()
{
Controls.Add(TextBox = new TextBox
{
Multiline = true,
Dock = DockStyle.Fill
});
ThrowUnhandledException(1);
ThrowUnhandledException(2);
ThrowUnhandledException(3);
}
private async void ThrowUnhandledException(int delaySeconds)
{
await Task.Delay(TimeSpan.FromSeconds(delaySeconds));
AppendText("Throwing a NotImplementedException!");
throw new NotImplementedException();
}
private TextBox TextBox { get; set; }
public void AppendText(string message)
{
TextBox.AppendText(message + Environment.NewLine);
}
}
편집을. 더 명확하게하기 위해 코드를 업데이트했습니다.
예외가 throw되면 MyForm은 TextBox에 다음과 같은 메시지를 씁니다. NotImplementedException을 Throw!
ThreadException 핸들러가 호출되면 다음과 같이 쓰여집니다. ThreadException 이벤트 핸들러가 호출되었습니다. 그리고 나서 메시지 상자를 보여줍니다. 모든 예외가 잡힌 경우
, 내 텍스트 상자는 다음 보여줄 것이다 :
Throwing a NotImplementedException! ThreadException event handler is called. Throwing a NotImplementedException! ThreadException event handler is called. Throwing a NotImplementedException! ThreadException event handler is called.
하지만 보여줍니다
Throwing a NotImplementedException! ThreadException event handler is called. Throwing a NotImplementedException! Throwing a NotImplementedException!
예, 그게 핵심입니다. ** MessageBox가 표시되면 ** 이벤트 핸들러가 호출되지 않습니다. 콘솔에 쓰고 핸들러에 메시지 상자를 표시하십시오. – yallie
@yallie 귀하의 요지를 봅니다. 'await ThrowUnhandledException (' – clearpath
)와 같이'await's를 사용하여 비동기 호출을 직렬화 해보십시오.이 코드 부분은 시뮬레이션에 불과합니다. 실제 응용 프로그램 이벤트는 비동기 적으로 발생합니다.비동기 서버 호출은 예외를 throw합니다. – yallie