【发布时间】:2014-05-09 07:22:10
【问题描述】:
这是我的代码:
private static Stopwatch _stopwatch;
static void PrintException(Exception ex)
{
Console.WriteLine(_stopwatch.Elapsed);
Console.WriteLine(ex);
}
static void ThrowException1()
{
throw new InvalidAsynchronousStateException();
}
static void ThrowException2()
{
throw new NullReferenceException();
}
static async Task ExecuteTask1()
{
await Task.Delay(1000);
ThrowException1();
}
static async Task ExecuteTask2()
{
await Task.Delay(2000);
ThrowException2();
}
static async Task Execute()
{
var t1 = ExecuteTask1();
var t2 = ExecuteTask2();
try
{
await t2;
}
catch (NullReferenceException ex)
{
// the NullReferenceException will be captured
Console.WriteLine("==============");
PrintException(ex);
}
}
static void Main(string[] args)
{
TaskScheduler.UnobservedTaskException += (sender, ev) => PrintException(ev.Exception);
_stopwatch = Stopwatch.StartNew();
Execute();
while (true)
{
Thread.Sleep(5000);
GC.Collect();
}
}
其实我并没有在Execute方法中等待t1,但它似乎仍然被执行,因为我在大约五秒后捕获了AggregateException。
谁能告诉我 t1 是什么时候被执行的?就我而言,打印到控制台的异常顺序是 1.NullReferenceException 2.AggregateException
【问题讨论】:
-
注意:
NullReferenceException是一个保留的异常,因此不应从用户代码中抛出。 -
@SriramSakthivel +1,我只是用于演示目的。
标签: c# async-await