0

I have a question about both keywords (Async and Await) Their main goal is to make more than one method to be done at the same time as i understood, so for example if i'm going to do a long task which will prevent the main task from being executed in that case i have to use (Async and Await).

But when I tried it in two different programs that do the same thing i found that the execution is the same w/o using (Async and Await)

first one

    class Async
{
    public Async()
    {
        main();
    }

    public async void main()
    {
        Console.WriteLine("Main Thread....");
        await SlowTask();
        Console.WriteLine("Back To Main Thread");
    }

    public async Task SlowTask()
    {
        Console.WriteLine("Useless Thread....");
        for (int i = 0; i < 1000000; i++)
        {
            // TODO
        }
        Console.WriteLine("Finished Useless Thread....");
    }
}

and the second

    class NoAsync
{
    public NoAsync()
    {
        main();
    }
    public void main()
    {
        Console.WriteLine("Main Thread....");
        SlowTask();
        Console.WriteLine("Back To Main Thread");
    }
    public void SlowTask()
    {
        Console.WriteLine("Useless Thread....");
        for (int i = 0; i < 1000000; i++)
        {
            // TODO
        }
        Console.WriteLine("Finished Useless Thread....");
    }
}

the execution of both are exactly the same, from what i understood that when using (Async and Await) both main and SlowTask will execute at the same time without waiting for one to end so the other start to execute but that doesn't happen.

What's wrong i've made or i'm miss-understanding Asynchronous in c# ? Kind regards.

  • The execution should not have been the same. Try again doing some actual work inside the loop. Maybe append to a string or something (Edit: Ignore this. It's wrong) – Joe Phillips Dec 05 '18 at 20:28
  • 1
    @JoePhillips why do you expect the execution to have been different? – Jonesopolis Dec 05 '18 at 20:30
  • Oh wait, it should actually be the same. It's doing the same amount of work both times. It's not until you are doing more than one thing that you reap benefits. Here's an example I wrote a while back: https://stackoverflow.com/questions/14455293/how-and-when-to-use-async-and-await/44204614#44204614 – Joe Phillips Dec 05 '18 at 20:32
  • I'm afraid you really do have many things that are issues in that code from an async perspective. People here can help correct them, but I'd suggest start by reading https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/ – sellotape Dec 05 '18 at 20:32
  • Actually, there is other bigger reason: *blocking*. All managed code in C# requires execution thread, *but some doesn't need thread at all*, so if you call something like File.WriteAllLines, it will mostly block until completed, but if you call async one - you will delegate execution to hard drive (reall one, in your computer, I mean physically delegate it) and free this thread for other job you might do. If you call other computer by TCP, there is no reason to wait for response, you just need to be notified. So await is basically subscription to result. Thats all. – eocron Dec 05 '18 at 20:33
  • @JoePhillips still the same after putting code inside the loop. the rest of main method doesn't execute until the SlowTask ends. – Ahmed Allam Dec 05 '18 at 20:33
  • I added https://stackoverflow.com/q/23048285/1260204 to the duplicate list because you are calling an async method from a constructor. The duplicates should explain to you how async/await works and when to use it. – Igor Dec 05 '18 at 20:47

2 Answers2

0

The execution should be exactly the same, they are logically consistent programs. There's likely not even a single task switch given your whole program is merely incrementing a counter variable.

Chris Marisic
  • 30,638
  • 21
  • 158
  • 255
0

I'd expect the execution of both to be the same. The issue is the latter, you have a misunderstanding of async in C#.

In short, when you await something in an async method, that thread is freed up to go do other stuff, until the awaited task finishes. But the program does not continue executing the next line until the awaited method completes. That would be bananas. You're thinking more of a background worker.

This can be handy, for example, when you are doing I/O and want a thread to be available to field http requests in the meantime. There is an abundance of reading material on this already. Here is a more in-depth answer

Jonesopolis
  • 23,589
  • 10
  • 63
  • 106
  • you mean that in my example the main method is freed from the memory until the await method is finished executing then it's called again to do it's work? – Ahmed Allam Dec 05 '18 at 20:45
  • @AhmedAllam In you were doing TaskA then TaskB, you could theoretically do them at the same time and have it run twice as fast. In your case you're only doing TaskA. You have to wait for that task to finish before your program can finish. There's no way to really speed that process up. – Joe Phillips Dec 05 '18 at 20:49
  • @JoePhillips so if i made taskB it will be working at the same time with the TaskA but will it give me it's result or i have to wait until the TaskA is finished ? – Ahmed Allam Dec 05 '18 at 20:56
  • @AhmedAllam The "await" keyword means "wait until this task is finished". If you don't use "await" the task will still run but it will not wait for it to finish. It will go to the next line. You could then store the task in a variable and get the results later on. This is what allows you to run multiple things at once without waiting between each step. – Joe Phillips Dec 05 '18 at 21:06
  • @JoePhillips now i got it, it was a miss-understand from me. Thank you. – Ahmed Allam Dec 05 '18 at 21:24