Friday, November 8, 2013

Async and await in .Net 4.5


Before moving ahead I want to introduce basic concept of Asynchronous Programming

 

Problem

Sometimes   in our web application we request for data from webserver and we have to wait for response. So in this case our entire application is blocked and user have to wait till response from webserver.

 

Solution

Asynchronous Programming is introduced to overcome above problem.

 


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

Difference between synchronous/asynchronous operations

a)      Synchronization means two or more operations are running in a same context (thread) so that one may block another

b)      Synchronization means two or more operations happen sequentially.

c)       Asynchronous means two or more operations are running in different contexts (thread) so that they can run concurrently and do not block each other.

  

Synchronous operation (fig 1)
Asynchronous operation (fig 2)
 
 



 

 Explanation

1)      From fig 1

a.       Each task occurs in sequence.

b.      Here from fig, step3 have to wait to complete step2

 

2)      From fig2

a.        async and await keywords has been introduced

b.      async and await are pair keywords. You cannot use them in a standalone manner.

c.       async is marked on a method. This keyword is just an indicator saying that this method will have the await keyword.

d.      The await keyword marks the position from where the task should resume. So you will always find this keyword in conjunction with Task.
        Here Step3 will execute without waiting for step2 to complete


 

No comments:

Post a Comment