[英]Debugger not breaking/stopping for exceptions in async method
When a debugger is attached to a .NET process, it (usually) stops when an unhandled exception is thrown. 当调试器附加到.NET进程时,它(通常)在抛出未处理的异常时停止。
However, this doesn't seem to work when you're in an async
method. 但是,当您使用
async
方法时,这似乎不起作用。
The scenarios I've tried before are listed in the following code: 我之前尝试的方案列在以下代码中:
class Program
{
static void Main()
{
// Debugger stopps correctly
Task.Run(() => SyncOp());
// Debugger doesn't stop
Task.Run(async () => SyncOp());
// Debugger doesn't stop
Task.Run((Func<Task>)AsyncTaskOp);
// Debugger stops on "Wait()" with "AggregateException"
Task.Run(() => AsyncTaskOp().Wait());
// Throws "Exceptions was unhandled by user code" on "await"
Task.Run(() => AsyncVoidOp());
Thread.Sleep(2000);
}
static void SyncOp()
{
throw new Exception("Exception in sync method");
}
async static void AsyncVoidOp()
{
await AsyncTaskOp();
}
async static Task AsyncTaskOp()
{
await Task.Delay(300);
throw new Exception("Exception in async method");
}
}
Am I missing something? 我错过了什么吗? How can I make the debugger to break/stop on the exception in
AsyncTaskOp()
? 如何使调试器在
AsyncTaskOp()
的异常中断/停止?
Under the Debug
menu, select Exceptions...
. 在“
Debug
菜单下,选择“ Exceptions...
。 In the Exceptions dialog, next to the Common Language Runtime Exceptions
line check the Thrown
box. 在“例外”对话框中,在“
Common Language Runtime Exceptions
行旁边,选中“ Thrown
框。
I would like to hear if anyone found out how to get around this issue? 我想知道是否有人知道如何解决这个问题? Perhaps a setting in latest visual studio...?
也许是最新视觉工作室的设置......?
A nasty but workable solution (in my case) was to throw my own custom Exception and then modify Stephen Cleary's answer: 一个令人讨厌但可行的解决方案(在我的情况下)是抛出我自己的自定义 Exception然后修改Stephen Cleary的答案:
Under the Debug menu, select Exceptions (You can use this Keyboard shortcut Control + Alt + E )... In the Exceptions dialog, next to the Common Language Runtime Exceptions line check the Thrown box.
在“调试”菜单下,选择“例外”(可以使用此键盘快捷键Control + Alt + E )...在“例外”对话框中,在“公共语言运行时例外”行旁边,选中“投掷”框。
to be more specific ie, add your custom Exception into the list, and then tick its "Thrown" box. 更具体一点,即将自定义 Exception添加到列表中,然后勾选其“Thrown”框。
Eg: 例如:
async static Task AsyncTaskOp()
{
await Task.Delay(300);
throw new MyCustomException("Exception in async method");
}
I have wrapped the anonymous delegate in a try/catch inside the Task.Run(() =>
. 我已经在
Task.Run(() =>
中的try / catch中包装了匿名委托。
Task.Run(() =>
{
try
{
SyncOp());
}
catch (Exception ex)
{
throw; // <--- Put your debugger break point here.
// You can also add the exception to a common collection of exceptions found inside the threads so you can weed through them for logging
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.