[英]Catching Exceptions of a Task that spawns an inner 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' ..." 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);
}
並測試它,例如通過
static void Main(string[] args)
{
AsyncTest test = new AsyncTest();
test.StartToOpen_Simple();
Console.WriteLine("Started async task. Waiting for exception");
Console.ReadKey();
}
我在VS2010調試器中運行時遇到一個非常煩人的問題:就像“摘要”狀態一樣,調試器在'tOpen'任務中拋出,相信我沒有捕獲異常(我在下面進一步說明) “在'tComplete'任務中)。 只有當我繼續調試會話時,才會看到異常“冒泡”並因此按需處理。 如果這個方法是在一個固定的時間間隔(它是!)上運行的,那么調試就變成了一場噩夢,因為調試器會在每個時間間隔內中斷。
在控制台上運行該程序,不會出現此行為。
第一次機會異常消息通常並不意味着代碼中存在問題。 對於優雅處理異常的應用程序/組件,第一次機會異常消息讓開發人員知道遇到並處理了異常情況。
請參考這個
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.