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