为什么我不能赶上从异步code异常? [英] Why can't I catch an exception from async code?

查看:115
本文介绍了为什么我不能赶上从异步code异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我到处都看它说了以下的code应该工作,但事实并非如此。

Everywhere I read it says the following code should work, but it doesn't.

public async Task DoSomething(int x)
{
   try
   {
      // Asynchronous implementation.
      await Task.Run(() => {
      throw new Exception();
      x++;
      });
   }
   catch (Exception ex)
   {
      // Handle exceptions ?
   }
}

这是说,我不是一无所获,并得到一个未处理的异常发起的'扔'线。我无言以对这里。

That said, I'm not catching anything and get an "unhandled exception" originating at the 'throw' line. I'm clueless here.

推荐答案

您有只是我的code选项打开。有了这个时,它正在考虑异常未处理的关于只是你的code - 因为其他code为捕捉异常和任务它内部的馅,后来在<$ C重新抛出$ C>计谋呼叫并捕获你的catch语句。

You have the "Just my code" Option turned on. With this on, it is considering the exception unhandled with respect to "just your code"--because other code is catching the exception and stuffing it inside of a Task, later to be rethrown at the await call and caught by your catch statement.

在不被连接在调试器,你的catch语句将被触发,它将运行如您所愿。或者,你可以在调试器中继续下去,它会按预期运行。

Without being attached in the debugger, your catch statement will be triggered, and it will run as you expect. Or you can just continue from within the debugger and it will run as expected.

更好的事情要做的就是仅仅关闭只是我的code。海事组织,它会导致更多的混乱比它的价值。

The better thing to do is to just turn off "Just my code". IMO, it causes more confusion than it is worth.

这篇关于为什么我不能赶上从异步code异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆