C# 5.0: async/await declarations

In order to enhance the possibilities of creation and the management of asynchronous processes and to simplify the code even more, version 5.0 of C# introduced a couple of new reserved words in order to facilitate the insertion of asynchronous calls without having to implement an extra method to receive the results: the couple of words are async/await (one cannot be used without the other).

When a method is marked as async, the compiler will check for the presence of another sentence prefixed with the await keyword. Although we write the method as a whole, the compiler fragments (internally) the method into two parts: the one where the async keyword appears initially, and the rest counting from the line in which await is used.

At execution time, as soon as the await sentence is found, the execution flow returns to the calling method and executes the sentences that follow, if any. As soon as the slow process returns, execution continues with the rest of sentences located next to the awaited statement.

We can view a brief initial sample of how it works in a transformation of the previous example (as I mentioned in relation with tasks, this topic will also be covered with more detail in the chapter dedicated to performance):

static void Main(string[] args)
{
  Console.WriteLine("SlowMethod started at...{0}",
    DateTime.Now.ToLongTimeString());
  SlowMethod();
  Console.WriteLine("Awaiting for SlowMethod...");
  Console.ReadLine();
}
static async Task SlowMethod()
{
  // Simulation of slow method "Sleeping" the thread for 3 secs.
  await Task.Run(new Action(() => System.Threading.Thread.Sleep(3000)));
  Console.WriteLine("Finished at: {0}", DateTime.Now.ToLongTimeString());
  return;
}

Note that I'm just writing the same code with a different syntax. When the execution flow reaches the first line of SlowMethod (marked as await), it launches another execution thread and returns to the thread in the calling method (Main). Consequently, we can see the Awaiting for SlowMethod message before the Finished at indication located at the end.

The output it is quite clear, as shown in the following screenshot:

C# 5.0: async/await declarations

Of course, as we indicated in relation with the Task object, there's much more to this than what is expressed here in this ephemeral introduction, and we'll cover this in Chapter 10, Design Patterns. But for now, we can have an idea about the benefits and simplification provided by this code construct.

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

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