TPL Break on unhandled exceptions

心已入冬 提交于 2020-01-01 12:07:15

问题


I am using async await as well as Task.Factory.StartNew in my application but one thing that i noticed changed is that visual studio is no more breaking when an unhandled exception occured

Here is what i mean by before using await

but after i turn a method into a Task and use await

It is only captured in the output area in visual studio...

BTW : It is very strange for me as i am new to .Net4.5 please excuse me if failed to illustrate what i need specifically but again what i want to know is

  • How could i make visual studio break on the exceptions when using async await

回答1:


When the debugger says "Exception was unhandled by user code", what it means is that an exception has propagated up to the framework. Since an async Task method places its exceptions on its returned Task, the exception does not propagate to the framework. An exception like this is unobserved.

If you want the debugger to break when exceptions are thrown, then use Debugger -> Exceptions -> Check the "Thrown" box for CLR Exceptions.

If you want to observe the exception, then change from TaskFactory.StartNew to Task.Run and call Wait on the returned Task. This will propagate the exception (wrapped in an AggregateException) through Main and up to the framework.




回答2:


That's why void returning async methods are evil.

On the first case the exception is not caught and the debugger is alerting you of just that.

On the second case it will be on the resulting task.

If you handle the exceptions inside the method you'll see similar behavior.

Task.Run is just a streamlined version of TaskFactory.StartNew: Task.Run vs Task.Factory.StartNew



来源:https://stackoverflow.com/questions/16328087/tpl-break-on-unhandled-exceptions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!