Wednesday 7 December 2016

Asynchronous Programming with async and await

Asynchrony is essential for activities that are potentially blocking, such as when your application accesses the web. Access to a web resource sometimes is slow or delayed. If such an activity is blocked within a synchronous process, the entire application must wait. In an asynchronous process, the application can continue with other work that doesn't depend on the web resource until the potentially blocking task finishes.
There are following areas where asynchronous programming improves responsiveness.
Application area
Supporting APIs that contain async methods
Web access
Working with files
Working with images
WCF programming

Asynchrony proves especially valuable for applications that access the UI thread because all UI-related activity usually shares one thread. If any process is blocked in a synchronous application, all are blocked. Your application stops responding, and you might conclude that it has failed when instead it's just waiting.
When you use asynchronous methods, the application continues to respond to the UI. You can resize or minimize a window, for example, or you can close the application if you don't want to wait for it to finish.
The async and await keywords in C# are the heart of async programming. By using those two keywords, you can use resources in the .NET Framework or the Windows Runtime to create an asynchronous method almost as easily as you create a synchronous method. Asynchronous methods that you define by using async and await are referred to as async methods.

Example1.
class Program
    {
        static void Main(string[] args)
        {
            Program p=new Program();
            p.DispTask();
            Console.WriteLine("hello");

            Console.ReadLine();
        }

        public async void DispTask()
        {

          Console.WriteLine("disp");
          Task t = test();
         
            // using await control will go to caller method and here it will suspend . once task completed again control will be here.
           await t;
            Console.WriteLine("disp after vali");
        }

        public async Task test()
        {
           // using await control will go to caller method (DispTask) and here it will suspend . once task completed again control will be here.
           await Task.Delay(30000);
            Console.WriteLine("test");
        }

    }

Example 2
// Three things to note in the signature:  
//  - The method has an async modifier.   
//  - The return type is Task or Task<T>. (See "Return Types" section.)  
//    Here, it is Task<int> because the return statement returns an integer.  
//  - The method name ends in "Async."  
async Task<int> AccessTheWebAsync()  
{   
    // You need to add a reference to System.Net.Http to declare client.  
    HttpClient client = new HttpClient();  
  
    // GetStringAsync returns a Task<string>. That means that when you await the  
    // task you'll get a string (urlContents).  
    Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");  
  
    // You can do work here that doesn't rely on the string from GetStringAsync.  
    DoIndependentWork();  
  
    // The await operator suspends AccessTheWebAsync.  
    //  - AccessTheWebAsync can't continue until getStringTask is complete.  
    //  - Meanwhile, control returns to the caller of AccessTheWebAsync.  
    //  - Control resumes here when getStringTask is complete.   
    //  - The await operator then retrieves the string result from getStringTask.  
    string urlContents = await getStringTask;  
  
    // The return statement specifies an integer result.  
    // Any methods that are awaiting AccessTheWebAsync retrieve the length value.  
    return urlContents.Length;  
}  
If AccessTheWebAsync doesn't have any work that it can do between calling GetStringAsync and awaiting its completion, you can simplify your code by calling and awaiting in the following single statement.
string urlContents = await client.GetStringAsync();  
The following characteristics summarize what makes the previous example an async method.
  • The method signature includes an async modifier.
  • The name of an async method, by convention, ends with an "Async" suffix.
  • The return type is one of the following types:
    • Task<TResult> if your method has a return statement in which the operand has type TResult.
    • Task if your method has no return statement or has a return statement with no operand.
    • Void if you're writing an async event handler.
  • The method usually includes at least one await expression, which marks a point where the method can't continue until the awaited asynchronous operation is complete. In the meantime, the method is suspended, and control returns to the method's caller. The next section of this topic illustrates what happens at the suspension point.
If you specify that a method is an async method by using an async modifier, you enable the following two capabilities.
  • The marked async method can use 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.
In .NET Framework programming, an async method typically returns a Task or a Task<TResult>. Inside an async method, an await operator is applied to a task that's returned from a call to another async method.
You specify Task<TResult> as the return type if the method contains a return statement that specifies an operand of type TResult.
You use Task as the return type if the method has no return statement or has a return statement that doesn't return an operand.
The following example shows how you declare and call a method that returns a Task<TResult> or a Task.
// Signature specifies Task<TResult>  
async Task<int> TaskOfTResult_MethodAsync()  
{  
    int hours;  
    // . . .  
    // Return statement specifies an integer result.  
    return hours;  
}  
  
// Calls to TaskOfTResult_MethodAsync  
Task<int> returnedTaskTResult = TaskOfTResult_MethodAsync();  
int intResult = await returnedTaskTResult;  
// or, in a single statement  
int intResult = await TaskOfTResult_MethodAsync();  
  
// Signature specifies Task  
async Task Task_MethodAsync()  
{  
    // . . .  
    // The method has no return statement.    
}  
  
// Calls to Task_MethodAsync  
Task returnedTask = Task_MethodAsync();  
await returnedTask;  
// or, in a single statement  
await Task_MethodAsync();  

An async method that has a void return type can’t be awaited, and the caller of a void-returning method can't catch any exceptions that the method throws.
An async method can't declare ref or out parameters, but the method can call methods that have such parameters.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.