Max*_*ing 3 c# win-universal-app uwp
我正在为 Unhandled Exception 事件编写处理程序,我们会将异常转储到文件中,然后发送到服务器进行进一步分析。现在它只会显示崩溃已经发生。我订阅了这个活动。在那个方法中,我调用了一个处理错误的函数。但是,当我在方法中编写此代码时:
public async Task HandleException(Exception exception)
{
var dialog = new MessageDialog(exception.Message, "Exception occurred");
await dialog.ShowAsync();
}
Run Code Online (Sandbox Code Playgroud)
并在调试模式下运行它,Visual Studio 会显示 Visual Studio 即时调试器。首先,我认为这是我试图在 GUI 线程死亡时显示消息框的问题。我将功能更改为:
public async Task HandleManagedException(Exception
{
await FileStorage.WriteToFileAsync("someFile.txt", exception.ToString());
}
Run Code Online (Sandbox Code Playgroud)
其中函数 FileStorage.WriteToFileAsync 看起来像:
public async Task WriteToFileAsync(string filename, string data)
{
var file = await this.storageFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(file, data);
}
Run Code Online (Sandbox Code Playgroud)
在调试器模式下,当我在await FileIO.WriteTextAsync(file,data)它上面放置断点时就停在那里。按下继续按钮后,显示与前面代码相同的窗口。从 XAML 事件调用它时,它运行正常。我在未处理的异常处理程序中搜索了 google 和 StackOverflow 中的异步方法,但没有任何与我的问题相关的内容。
我的问题是:该错误的原因是什么?是否可以在 Unhandled 异常处理程序中使用异步方法?
更新: 感谢您到目前为止的回答。关闭调试代码后我自己回答的第二个问题。事实证明这是可能的,并且该功能按预期工作。
为了避免 Visual Studio 即时调试器对话框,我们可以将UnhandledExceptionEventArgs.Handled属性设置为true如下所示:
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
this.UnhandledException += App_UnhandledException;
}
private async void App_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
e.Handled = true;
await HandleException(e.Exception);
}
public async Task HandleException(Exception exception)
{
var dialog = new MessageDialog(exception.Message, "Exception occurred");
await dialog.ShowAsync();
}
Run Code Online (Sandbox Code Playgroud)
在调试模式下,您会看到警告和即时调试器对话框,因为App.gics 中有以下代码:
#if DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION
UnhandledException += (sender, e) =>
{
if (global::System.Diagnostics.Debugger.IsAttached)
global::System.Diagnostics.Debugger.Break();
};
#endif
Run Code Online (Sandbox Code Playgroud)
这些代码是在我们构建项目时自动生成的。从这些代码中,我们可以发现在调试模型中,如果有任何未处理的异常,它将调用Debugger.Break 方法,这将导致警告和即时调试器对话框。
e.Handled = true;在我们的处理程序中设置可以避免这种情况。有关更多信息,您可以查看这个类似的问题:How to try/catch all exceptions。但是,正如您所看到的,这只会在调试模式下发生,在发布模式下,您的代码应该运行良好。