Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What if not await the task?

Tags:

c#

async-await

Here is my code:

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();
    }
}

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.

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

like image 393
Jerry Bian Avatar asked Nov 30 '22 19:11

Jerry Bian


1 Answers

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 is only used to (asynchronously) wait for the completion of a task. It does not start tasks.

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

like image 88
Stephen Cleary Avatar answered Dec 05 '22 07:12

Stephen Cleary