如果不等待任务怎么办?

Jer*_*ian 3 c# async-await

这是我的代码:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

其实,我并没有期待t1Execute的方法,但现在看来,这仍然执行,因为我拍摄的AggregateException约五秒钟后.

t1执行时有人能告诉我吗?在我的情况下,打印到控制台的例外订单是1 NullReferenceException.AggregateException

Ste*_*ary 10

在异步/等待世界中,任务是"热门".因此,当您致电时ExecuteTask1,已经处理了返回给您的任务.它已经开始了.你可以Console.WriteLine在开始时ExecuteTask*看到它们立即开始.

await只是用来(异步)等待完成任务的.它不会启动任务.

我在我的博客上有一个async介绍,你可能会觉得有帮助.