Asynchronous programming with the async and await keywords

The async and await keywords were announced in C# 5.0 and became the latest and greatest things in C# asynchronous programming. Developed from the TAP pattern, C# integrates these two keywords into the language itself so that it makes it simple and easy to read. Using these two keywords, the Task and Task<TResult> classes still become the core building blocks of asynchronous programming. We will still build a new Task or Task<TResult> data type using the Task.Run() method, as discussed in the previous section.

Now let's take a look at the following code, which demonstrates the async and await keywords, which we can find in the AsyncAwait.csproj project:

public partial class Program 
{ 
  static bool IsFinish; 
  public static void AsyncAwaitReadFile() 
  { 
    IsFinish = false; 
    ReadFileAsync(); 
    //do other work while file is read 
    int i = 0; 
    do 
    { 
      Console.WriteLine("Timer Counter: {0}", ++i); 
    } 
    while (!IsFinish); 
    Console.WriteLine("End of AsyncAwaitReadFile() method"); 
  } 
  public static async void ReadFileAsync() 
  { 
    FileStream fs = 
      File.OpenRead( 
      @"......LoremIpsum.txt"); 
    byte[] buffer = new byte[fs.Length]; 
    int totalBytes = 
      await fs.ReadAsync( 
      buffer, 
      0, 
      (int)fs.Length); 
    Console.WriteLine("Read {0} bytes.", totalBytes); 
    IsFinish = true; 
    fs.Dispose(); 
  } 
} 

As we can see in the preceding code, we refactor the code from our previous topic by adding the await keyword when we read the file stream, as shown in the following code snippet:

int totalBytes = 
  await fs.ReadAsync( 
    buffer, 
    0, 
    (int)fs.Length); 

Also, we use the async keyword in front of the method name, as shown in the following code snippet:

public static async void ReadFileAsync() 
{ 
  // Implementation 
} 

From the preceding two code snippets, we can see that the await keyword can only be called inside a method that is marked with the async keyword. And when await is reached--in this case, it is in await fs.ReadAsync()--the thread that called the method will jump out of the method and continue on its way to something else. The asynchronous code then takes place on a separate thread (like how we use the Task.Run() method). However, everything after await is scheduled to be executed when the task is finished. And if we run the preceding AsyncAwaitReadFile() method, we will get the following output on the console:

Asynchronous programming with the async and await keywords

As with the TAP model, we obtain the asynchronous result here as well.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset