0

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?

user3856437
  • 2,071
  • 4
  • 22
  • 27
  • 2
    `await`, waits for it to complete – mxmissile Oct 22 '21 at 21:46
  • `Refresh()` on `await TestOnly();` will wait all 10 sec, then write "2 Written" then return 100 and THEN run `await TestAgain();`. Either if you `Task.Run(async () => await TestOnly());` (without `await` before `Task.Run`) - it wouldn't wait for completion. – Auditive Oct 22 '21 at 21:51
  • The explanation about async/await really confuses me because I though it will not wait but move to the next code to execute. – user3856437 Oct 22 '21 at 21:53
  • If you want to await multiple tasks at once, there's also the static method [`Task.WaitAll`](https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.waitall?view=net-5.0) and its various overloads. – Powerlord Oct 22 '21 at 21:57
  • As far as program flow is concerned, `await` is very much as if the thread were blocked. It's *not* actually blocked; the thread is free to go off and do other things until the awaited task is complete. When the task is complete, a thread (maybe the same one, maybe a different one) resumes executing your program at the next instruction after the `await`. – Tech Inquisitor Oct 22 '21 at 21:57
  • What do you think `await` does? You've described what would happen if the `await` wasn't even there. If it didn't do *anything* people wouldn't use it. – Servy Oct 22 '21 at 22:55

1 Answers1

3

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?

John Wu
  • 50,556
  • 8
  • 44
  • 80