In the Previous post, we learned about Validation with Jquery. In the Current post, we will learn a new feature of C sharp in .net framework 4.5. 

Introduction to Async and Await

Async and await are two new keywords that are introduced with .net framework 4.5 for supporting asynchronous programming. We can use Async feature which makes asynchronous programming straightforward as synchronous programming.

Async modifier specifies that method is an async method and returns a Task or Task. Task or Task return type hold information regarding ongoing work of methods i.e. Task contains information that the caller of the method can use status of Task, its unique ID and method's result.

async Task<int> DoSomeTasksAsync()

Await operator is used with return task in an await expression. This expression suspends execution of the method that contains it until the awaited task is complete. In mean time controls is returned to the caller of the suspended method.

Task<int> taskobject=  DoSomeTasksAsync()
int taskResult = await taskobject;

 

Background of Async Programming with Delegate.

Previously, writing asynchronous code has required you to define callbacks (also referred to as continuations) to capture what occurs after an asynchronous process finishes. This complicates your code and makes routine tasks, such as exception handling, awkward and difficult. As below code. If you want to use call a method asynchronously then you will have to create a callback method and on completion of task Call Back method is called. But If you use the Async feature, the compiler does most of the work for you.

           { 
              // Create an instance of the test class which is having Test Method that will be called asynchronously.
            AsyncDemo ad = new AsyncDemo();
             // AsyncMethodCaller is delegate that will be used to call method asynchronously 
            AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);
            int dummy = 0;
             // BeginInvoke is used to start execution of methods asynchronously. When execution of ad.TestMethod finish that CallbackMethod will be called. 
            IAsyncResult result = caller.BeginInvoke(3000,
                out dummy, 
                new AsyncCallback(CallbackMethod),
                "The call executed on thread {0}, with return value \"{1}\".");
            Console.WriteLine("The main thread {0} continues to execute...", 
                Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(4000);
            Console.WriteLine("The main thread ends.");
           }
           static void CallbackMethod(IAsyncResult ar) 
           {
              // Do Some work here.
           }

Code Example of Async and Await with C sharp.

When an application access web than access of some resource delayed the process and if some resource is blocked for some time than whole application has to wait for that. So in such case asynchrony is essential for activities that are potentially blocking such as HttpClient, StreamReader, and XmlReader etc. To Improve the process of application we can use Async and await as using Async Methods are easy to write. To Create Async Methods Three things should be followed. 1. The method must have a sync Modifier. 2. The return type of method should be Task or Task. Where TResult is a Generic type that can be replaced with any type. i.e. Task or Task 3. Method name should end up with Async. This is not mandatory but Guideline only

async Task<string> FetchStringFromWebAsync()
{ 
    HttpClient client = new HttpClient();
    // GetStringAsync returns a Task. That means that when you await the 
    // task you'll get a string (urlContents).
    Task<string> getString = client.GetStringAsync("http://google.com");
    // You can do work here that doesn't rely on the string from GetStringAsync.
    DoAnyWorkHere();
    // The await operator suspends FetchStringFromWebAsync 
    //  - FetchStringFromWebAsync can't continue until getString is complete. 
    //  - Meanwhile, control returns to the caller of FetchStringFromWebAsync. 
    //  - Control resumes here when getString is complete.  
    //  - The await operator then retrieves the string result from getString. 
    string urlContents = await getString;
    // The return statement specifies an String result. 
    // Any methods that are awaiting FetchStringFromWebAsync retrieve the content value. 
    return urlContents;
}

If you don't have any work to do between this call that then you can shorten your code by writing

HttpClient client = new HttpClient();
string urlContents = await client.GetStringAsync();

Async methods are intended to be non-blocking operations. An await expression in an async method doesn’t block the current thread while the awaited task is running. Instead, the expression signs up the rest of the method as a continuation and returns control to the caller of the async method.

I hope above information will be helpful for you people to understand the basic idea of async and wait.

Latest on posts

Blog Archive

Tags