【发布时间】:2015-08-19 03:35:21
【问题描述】:
我有一个基本框架,旨在通用地处理错误;但是,当错误发生时,我似乎没有在我的框架中捕获它。以下代码是我想要实现的简化版本:
class Program
{
static void Main(string[] args)
{
RunMethod<decimal>(() =>
{
decimal x = 0;
decimal y = 1 / x;
return y;
});
}
private static async Task<T> RunMethod<T>(Func<T> method)
{
try
{
var result = await TryRunningMehod<T>(method);
return result;
}
catch (DivideByZeroException ex)
{
System.Diagnostics.Debug.WriteLine("Error");
return default(T);
}
}
private static async Task<T> TryRunningMehod<T>(Func<T> method)
{
var returnValue = await Task.Run<T>(method);
return returnValue;
}
}
当您运行上述代码时会发生什么情况,它会在除以零时崩溃。我正在尝试让它写一条调试消息并继续。
我只标记了未处理的异常。
我的例外设置:
IDE 崩溃时的样子:
【问题讨论】:
-
无论你“标记”什么,都不是你想的那样。我的水晶球说您在“调试”>“例外”对话框中勾选了“抛出”复选框。这使得调试器在抛出异常时停止,然后才能到达 catch 块。您需要解决此代码中的真正错误,您的程序在任务完成之前结束。
-
我不止一次检查过我没有那个标志。在这个例子中,任务结束的时间基本上是无关紧要的,因为它会出错——这是测试的目的(它所基于的代码确实等待函数)
-
您没有等待
RunMethod完成,这意味着您的应用程序在您除以零时已经终止。
标签: c# .net asynchronous anonymous-methods