Async and Await Sample

If you specify that a method is an async method by using an Async or async modifier, you enable the following two capabilities. The marked async method can use Await or await to designate suspension points. The await operator tells the compiler that the async method can’t continue past that point until the awaited asynchronous process is complete. In the meantime, control returns to the caller of the async method. The suspension of an async method at an await expression doesn’t constitute an exit from the method, and finally blocks don’t run. The marked async method can itself be awaited by methods that call it.
An async method typically contains one or more occurrences of an await operator, but the absence of await expressions doesn’t cause a compiler error. If an async method doesn’t use an await operator to mark a suspension point, the method executes as a synchronous method does, despite the async modifier. The compiler issues a warning for such methods. Async and await keywords in C# are intended to help with offloading long IO operations off the UI thread.

public class Customer
    public string FirstName { getset; }
    public string LastName { getset; }
    public async void GetCustomer()
        Customer cust = await this.GetCustomerFromService();
    private Task<Customer> GetCustomerFromService()
        Task<Customer> taskGetCustomer = new Task<Customer>(() =>
            Console.WriteLine("Calling Customer Service");
            Customer cust = new Customer()
                FirstName = "Aamol",
                LastName = "Gote"
            Console.WriteLine("Customer Service returned Customer");
            return cust;
        return taskGetCustomer;
class Program
    static void Main(string[] args)
        Console.WriteLine("Main UI Thread");
        Customer cust = new Customer();
        Console.WriteLine("Main UI Thread - Post Get Customer Call");

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s