Welcome to Blogs @ Andrew Qu
Blog Index
All blogs
Search results

New Asynchronous Programming Model(async and await) in VS2012

Summary

Visual Studio 2012 introduces a new model for asynchronous programming. This blog uses a simple example to show the workings of the new model.

The Example

Open Visual Studio 2012(You can download free Release Preview copies). Create a new C# console application. Add the following code:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Program started");
        AsyncMethod1();
        Console.WriteLine("Returned from AsyncMethod1()");
        Thread.Sleep(8000);
        Console.WriteLine("Program end");
    }
    static async void AsyncMethod1()
    {
        int i = await AsyncMethod2();
        Console.WriteLine("End of AsyncMethod1() i={0}", i);
    }
    static async Task <int> AsyncMethod2()
    {
        await Task.Run(() => { Thread.Sleep(5000); });
        return 2;
    }
}
Run the program, you should see this output:
Program started
Returned from AsyncMethod1()
End of AsyncMethod1() i=2
Program end
Press any key to continue . . .
The Execution Timeline

Some Explanation
  • Any asynchronous method must be preceeded by modifier async.
  • await can only preceed a Task.
  • await suspends the current method immediately and returns control to the caller.
  • When the awaited task is complete, await resumes the method excution and executes anything after the await line.
  • In our example, Main() starts and calls into AsyncMethod1().
  • AsyncMethod1() returns on the first line without executing Concole.WriteLine()
  • Control returns to Main() and writes Returned from AsyncMethod1() immediately. Then Main() Sleeps for 8s
  • While Main() is Sleeping, AsyncMethod2() completes after 5s and returns value 2.
  • The task in AsyncMethod1() is complete and execution resumes and write "End of AsyncMethod1() i=2".
  • Another 3s later, Main() wakes up and writes "Program end".
Example with Task Manipulation

Tasks can be manipulated. To illustrate this, the example is modified as shown in the following listing. Now in Main(), instead of Sleep(8000), we periodically check if the task is complete. We end the program only when the task is complete.

To do this, we added a task variable. The task variable is assigned a task in AsyncMethod1(). We then check the task's IsComplete property. When it is true, we break from the while loop and exit the program.

class Program
{
    private static Task <int>  task;

    static void Main(string[] args)
    {
        Console.WriteLine("Program started");
        AsyncMethod1();
        Console.WriteLine("Returned from AsyncMethod1()");
        while (task.IsCompleted == false)
        {
            Thread.Sleep(500);
        }
        Console.WriteLine("Program end");
    }
    static async void AsyncMethod1()
    {
        task = AsyncMethod2();
        int i = await task;
        Console.WriteLine("End of AsyncMethod1() i={0}", i);
    }
    static async Task <int> AsyncMethod2()
    {
        await Task.Run(() => { Thread.Sleep(5000); });
        return 2;
    }
}
Ads from Google
Dr Li Anchor Profi
www.anchorprofi.de
Engineering anchorage plate design system
©Andrew Qu, 2015. All rights reserved. Code snippets may be used "AS IS" without any kind of warranty. DIY tips may be followed at your own risk.