Sim*_*ord 3 .net c# asynchronous task async-await
我正在尝试从任务中实现异常处理,但我似乎无法正确处理。我找到了一些该模式的例子,但无论我尝试什么,我似乎总是从任务本身中得到未处理的异常。我一定错过了什么,但我看不到什么。任何帮助将不胜感激。
我试过在 MSDN 上找到的一个例子,但这对我不起作用:
https://msdn.microsoft.com/en-us/library/dd997415(v=vs.110).aspx
我遵循了这个问题的答案,但是当我在 Visual Studio 中运行修复程序时,它仍然抱怨未处理的异常:
ContinueWith TaskContinuationOptions.OnlyOnFaulted 似乎没有捕获从启动的任务抛出的异常
这是我最初编写的代码:
static void Main(string[] args)
{
TestAsync().ContinueWith(t =>
{
Console.WriteLine(t.Exception.ToString());
}, TaskContinuationOptions.OnlyOnFaulted);
Console.ReadKey();
}
static async Task<IEnumerable<string>> TestAsync()
{
IEnumerable<string> list = null;
try
{
list = await TestTask();
}
catch (Exception)
{
Console.WriteLine("Caught!");
}
return list;
}
static Task<IEnumerable<string>> TestTask()
{
var task = new Task<IEnumerable<string>>(() =>
{
throw new AggregateException("This is a test");
});
task.Start();
return task;
}
Run Code Online (Sandbox Code Playgroud)
在 VS 中断后点击继续,你会看到它进入你的 ContinueWith。这只是调试器的一个怪癖,因为它无法在处理执行的代码中找到 try/catch。
如果您不希望调试器停止并向您显示一条消息,您将需要在调试器选项中禁用“仅我的代码”,以便将位于其中的 try/catchTask计为捕获异常的内容。
| 归档时间: |
|
| 查看次数: |
1268 次 |
| 最近记录: |