如果不等待任务该怎么办? [英] What if not await the task?

查看:99
本文介绍了如果不等待任务该怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

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.

Actually, I didn't await t1 in Execute method, but it seems it was still executed, since I captured the AggregateException about five seconds later.

有人可以告诉我t1执行的时间吗?在我的情况下,打印到控制台的异常顺序为1.NullReferenceException2.AggregateException

Can someone tell me when the t1 was executed? In my case, the exceptions order which printed to the Console is 1. NullReferenceException 2. AggregateException

推荐答案

在异步/等待世界中,任务很热".因此,当您调用ExecuteTask1时,已经处理了返回给您的任务.在这一点上它已经开始.您可以将Console.WriteLine放在ExecuteTask*的开头,以确保它们确实可以立即开始.

In the async/await world, tasks are "hot". So, when you call ExecuteTask1, the task returned to you is already being processed. It has already started at that point. You can put a Console.WriteLine at the beginning of ExecuteTask* to see that they do start immediately.

await仅用于(异步)等待任务的完成.它不会开始任务.

await is only used to (asynchronously) wait for the completion of a task. It does not start tasks.

我的博客上有一个 async简介,可能会对您有所帮助

I have an async intro on my blog that you may find helpful.

这篇关于如果不等待任务该怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆