C# 捕获生成内部任务的任务的异常
给出以下简化代码C# 捕获生成内部任务的任务的异常,c#,.net,exception-handling,task-parallel-library,task,C#,.net,Exception Handling,Task Parallel Library,Task,给出以下简化代码 /// <summary> /// Within the VS2010 debugger, the following test will cease with an /// "Exception was unhandled by user code". /// (Debug window reports a "A first chance exception of type /// 'System.Exception'
/// <summary>
/// Within the VS2010 debugger, the following test will cease with an
/// "Exception was unhandled by user code".
/// (Debug window reports a "A first chance exception of type
/// 'System.Exception' ..." BEFORE the exception is caught
/// further down in the execution path.)
/// OUTSIDE the VS2010 debugger, the exception is caught by the tComplete
/// task that follows the tOpen task, just as expected.
/// </summary>
public void StartToOpen_Simple()
{
Task tOpen = Task.Factory.StartNew(() => {
//do some work before spawning another task here
try
{
return Task.Factory.StartNew(() => {
Thread.Sleep(2000);
//First chance exception occurs here:
throw new Exception("Some generic exception");
}, TaskCreationOptions.AttachedToParent);
} catch (Exception ex)
{
//never fires
var source = new TaskCompletionSource<object>();
source.TrySetException(ex);
return source.Task;
}
}).Unwrap();
Task tComplete = tOpen.ContinueWith(t => {
if (t.Exception != null)
{
Exception LastOpenException = t.Exception.Flatten().GetBaseException();
if (LastOpenException is OperationCanceledException)
{
Console.WriteLine("OperationCanceledEx: " + LastOpenException.Message);
} else
{
Console.WriteLine("Some exception occured in the tOpen task, but we're prepared for it here in the tComplete task.");
Console.WriteLine("The exception message was: {0}", LastOpenException.Message);
}
} else
{
//do something if no exception occured (doesn't happen in this example)
}
}, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.AttachedToParent, TaskScheduler.Default);
}
在VS2010调试器中运行它时,我发现了一个非常恼人的问题:就像“摘要”状态一样,调试器在抛出“tOpen”任务时中断,认为我没有捕获异常(我在“tComplete”任务中“在下面”执行此操作)。只有当我继续调试会话时,我才能看到异常是“冒泡”的,因此可以根据需要进行处理。如果这个方法是在一个固定的时间间隔上运行的(事实就是这样!),那么调试就会变成一场噩梦,因为调试器会在每个时间间隔中断
在控制台上运行该程序不会表现出这种行为
第一次机会异常消息通常并不意味着代码中存在问题。对于优雅地处理异常的应用程序/组件,first chance异常消息让开发人员知道遇到并处理了异常情况
请参考我知道,Matt,但是,如果调试器(如本例中)认为未捕获此异常,则调试器中断时,第一次机会异常会变成第二次机会异常。正是这种行为使调试成为一场噩梦。我仍然在寻找关于如何最好地“控制”这种行为的提示。
static void Main(string[] args)
{
AsyncTest test = new AsyncTest();
test.StartToOpen_Simple();
Console.WriteLine("Started async task. Waiting for exception");
Console.ReadKey();
}