我想运行多个任务,其中一些任务可以完成异步,然后等待所有任务完成。由于任务可能会引发异常,因此我想捕获并记录它们。 sample code for that:
static async Task doit(int x)
{
try
{
Console.WriteLine("{0} {1} start", x, Thread.CurrentThread.ManagedThreadId);
await Task.Run(() =>
{
Thread.Sleep(TimeSpan.FromSeconds(2 + x)); // simulate long-running stuff worth awaiting...
if (x == 3)
{
throw new Exception("Exception inside task " + x.ToString()); // Simulate the async task throwing exception
}
});
if (x == 2)
{
throw new Exception("Exception after task " + x.ToString()); // Simulate post-async task throwing exception
}
Console.WriteLine("{0} {1} end", x, Thread.CurrentThread.ManagedThreadId);
}
catch (Exception ex)
{
Console.WriteLine("{0} {1} Exception: {2}", x, Thread.CurrentThread.ManagedThreadId, ex.Message);
}
}
private static void TestTasks()
{
var tasks = Enumerable.Range(1, 3).Select(n => doit(n)).ToArray();
Console.WriteLine("Waiting");
Task.WaitAll(tasks);
Console.WriteLine("all end");
}
如果我从控制台运行此代码,它将按预期工作,并输出以下内容:
1 1 start
2 1 start
3 1 start
Waiting
1 3 end
2 4 Exception: Exception after task 2
3 5 Exception: Exception inside task 3
all end
但是,如果我在 Visual Studio 中进行调试,调试器会在注意到的异常处停止Exception was unhandled by user code
。那我需要打F5 Continue
以便代码完成。
我注意到,如果我禁用选项=>调试器=>Enable Just My Code
,调试器不会停止。但是,我不想永久设置它,因为我使用的一些框架处理我的异常do希望调试器停止。
- 为什么即使异常位于 try/catch 内,调试器也会停止?
- 如何让调试器不因该异常而停止?