0

The below code example is reading from a file. It works - but can anyone explain what the advantage of the await? I mean, the code anyways would 'wait' for the file-reading to return a result, so what does it change to use the await? Can I add something to this example, to better illustrate the purpose of the await?

using System;
using System.IO;
using System.Threading.Tasks;

class Program
{
    static void Main()
    {
        Task task = new Task(CallMethod);
        task.Start();
        task.Wait();
        Console.ReadLine();
    }

    static async void CallMethod()
    {
        string filePath = "C:\\Temp\\sampleFile.txt";
        Task<int> task = ReadFile(filePath);

        Console.WriteLine("BEFORE");

        int length = await task;
        Console.WriteLine(" Total length: " + length);
    }

    static async Task<int> ReadFile(string file)
    {
        int length = 0;

        Console.WriteLine("File reading is starting");
        using (StreamReader reader = new StreamReader(file))
        {
            // Reads all characters from the current position to the end of the stream asynchronously
            // and returns them as one string.
            string s = await reader.ReadToEndAsync();

            length = s.Length;
        }
        Console.WriteLine("File reading is completed");
        return length;
    }
}
Peter Hansen
  • 29
  • 1
  • 4
  • Already addressed here https://stackoverflow.com/questions/28841345/benefits-of-using-async-and-await-keywords – Vilsad P P Dec 20 '21 at 04:56
  • [Avoid async void](https://learn.microsoft.com/en-us/archive/msdn-magazine/2013/march/async-await-best-practices-in-asynchronous-programming#avoid-async-void). It is intended for event handlers, and the `CallMethod` is not an event handler. – Theodor Zoulias Dec 20 '21 at 04:57
  • 2
    Does this answer your question? [Benefits of using async and await keywords](https://stackoverflow.com/questions/28841345/benefits-of-using-async-and-await-keywords) – touchofevil Dec 20 '21 at 05:05
  • 1
    Prefer YahooSerious answer in the linked duplicate – Caius Jard Dec 20 '21 at 05:19
  • 1
    *so what does it change to use the await?* - the thread that wants the data from the file can go off and do something else while it waits for the file data to be delivered, rather than sitting doing nothing. Computers would seem very slow if everything that was waiting for something sat around doing nothing instead of finding something else to do. If the photocopier runs out of paper, start boiling the kettle, then vacuum the carpet while you wait for amazon to deliver more paper, and the kettle to boil, rather than waiting for amazon, then reload the photocopier, then make tea, then carpet – Caius Jard Dec 20 '21 at 05:24
  • Note, this isn't multithreading; there is only one of you doing 3 jobs and moving onto another job if you get blocked. It would be way more expensive to hire 3 people to get those 3 jobs done, especially if one person sits and does nothing other than wait until amazon turns up and the other does nothing other than wait until the kettle finishes boiling. Console applications are always a crap way of visualizing the benefits of async because they only typically do one thing at once anyway. Do some loooong file operation in a Windows GUI app and see that the long op hangs the user interface – Caius Jard Dec 20 '21 at 05:30
  • @CaiusJard It means, the advantage of the await is, that it releases the thread (of which there are only a limited number available on the machine) and that all the other things running in the application are then less likely to run out of threads to run on? – Peter Hansen Dec 20 '21 at 06:18
  • 1
    Yes. Of course, you can create nore threads just like you can hire more employees, but it comes with a cost; it's better optimizing the jobs for a few threads/employees is more sensible than creating a new thread/employee whenever we've run out because everyone is busy doing nothing. Also, having fewer threads generally means programs are easier to write – Caius Jard Dec 20 '21 at 06:43

1 Answers1

0

Asynchronous code does not lock the current thread while waiting for an I/O request to complete (a request to the file system, or to the network, etc.).

The advantage is illustrated in what you are doing here:

Task<int> task = ReadFile(filePath);

Console.WriteLine("BEFORE");

int length = await task;

You're starting to read the file, but while you wait for a response from the file system, you can go do something else, like writing to the console.

Microsoft has a series of very well-written articles about Asynchronous programming with async and await. Read through those.

Some other comments about your code: You should avoid using async void. It doesn't allow you to know when the task finished (or if it finishes). So your task.Wait() doesn't actually do anything useful because of that.

Starting in C# 7.1, you can make the Main method async too, and use await CallMethod() instead of the 3 lines you have of creating the task.

Gabriel Luci
  • 38,328
  • 4
  • 55
  • 84
  • I actually did read the Microsoft articles, ant the breakfast prep example. It's just not very illustrative when you do not actually SEE the slowdown of something, when you are not runnung synchronously. – Peter Hansen Dec 25 '21 at 03:17