user3856437
user3856437

Reputation: 2377

In C# an async task waits to finish another async task before it executes

I have this test methods,

private async Task<int> TestOnly()
{
    await Task.Delay(10000);
    using (StreamWriter sw = File.AppendText(@"asyncTest.txt"))
    {
        sw.WriteLine($"2 Written TestOnly().");
    }

    return 100;
}

private async Task TestAgain()
{
    await Task.Delay(0);
    using (StreamWriter sw = File.AppendText(@"syncTest.txt"))
    {
        sw.WriteLine($"1 Written here TestAgain().");
    }
}

Private async Task Refresh()
{
    await TestOnly();
    await TestAgain();
}

If I call the Refresh(), what I am expecting that in syncTest.txt, the text 1 Written here TestAgain(). will print first than 2 Written TestOnly(). because the TestOnly() method awaiting 10 seconds before it writes into the asyncTest.txt. But when I run, it waits for it. Why is that?

Upvotes: 0

Views: 94

Answers (1)

John Wu
John Wu

Reputation: 52210

When you await a task, you cause execution of the current method to suspend until the task is completed. Don't await a task until you're ready to wait for it.

private async Task Refresh()
{
    var task1 = TestOnly();
    var task2 = TestAgain();
    await Task.WhenAll(task1, task2);
}

You can also accomplish the whole thing without async or await. If you can see why, I think it will help you understand what await does.

private Task Refresh()
{
    var task1 = TestOnly();
    var task2 = TestAgain();
    return Task.WaitAll(task1, task2);
}

This may also help: How do yield and await implement control of flow in .NET?

Upvotes: 3

Related Questions