Asynchronous programming Deep Dive part 1


In my previous ,post I had introduced the concept of the wait, wait all, wait any. Lets see a few of these in action. More over lets learn how to efficiently convert our own synchronous code to take the benefit asynchronous and parallel methodologies.

The app

clip_image001
We have a simple app which gets RSS feed of news from Google and BBC . I do not want to go into the

implementation details,or parsing of XML.If you want to see that, you can just download the code.

clip_image003

So Lets click “BBC News” and then “Google” Now, in the figure above you can see 2 numbers have appeared below the textbox. The numbers indicate the amount of milliseconds it took for the respective servers to reply with a response. As you can see , Google servers have a quite high latency of more than a second. The numbers in the textbox indicate the number of headlines.

Now the “Both” Button, synchronously fires both the requests one after the other .The typical time it takes is to the tune of almost 3000 miliseconds.

Now lets see the code. The code or the BBC button is as follows .

int time_start = System.Environment.TickCount;

String url = “http://feeds.bbci.co.uk/news/world/rss.xml?edition=uk#”;

WebResponse Response = getResponse(url);

textBox1.Text = processBBCNews(Response).ToString();

int time_stop = System.Environment.TickCount;

label1.Text = (time_stop – time_start).ToString();

Now, the code for Google News button is exactly same only the URL is different and the updation labels are different.

getResponse is an user defined function that sends the Http Get request and receives the response.processBBCNews extracts the title from the XML and puts each one into the List.

   1: private int processBBCNews(WebResponse Response)

   2:         {

   3:             listBox1.Items.Clear();

   4:             XmlReader rdr = XmlReader.Create(new System.IO.StreamReader(Response.GetResponseStream()));

   5:             int count = 0;

   6:             while (rdr.Read())

   7:             {

   8:  

   9:  

  10:                 if (rdr.Name.Equals("title"))

  11:                 {

  12:                     string a = rdr.ReadElementContentAsString();

  13:                     listBox1.Items.Add(a);

  14:                     count++;

  15:                 }

  16:             }

  17:             return count;

  18:         }

.In the code behind for the “both” button, we do exactly the something. We first send the HTTP get request for the Google News, then receive the response and process it. Then we fire off another GET Http request for BBC news and get the response. The total time taken is noted.

Now to convert synchronous code to asynchronous code

   1: private void button1_Click(object sender, EventArgs e)

   2:  

   3: {

   4:  

   5: int time_start = System.Environment.TickCount;

   6:  

   7: String url = "http://feeds.bbci.co.uk/news/world/rss.xml?edition=uk#";

   8:  

   9: //We have specified the return type of the code that will beexecuted in the task

  10:  

  11: //This allows us to use the Task as a function and implement encapsulation,

  12:  

  13: //hence variables thar are used inside do not need to be declared outside

  14:  

  15: Task<WebResponse> T = Task<WebResponse>.Factory.StartNew(() =>

  16:  

  17: {

  18:  

  19: WebResponse Response = getResponse(url);

  20:  

  21: return Response;

  22:  

  23: });

//As we know, that processing of results can only occur when the Response is

//recieved ,hence instead of using

//callbacks we are using continue with.In my series,I will you to think in terms

//of continuations and not callbacks

//Here antecedent refers to the task thats just finished .

   1: Task T2 = T.ContinueWith((antecedent) =>

   2:  

   3: {

   4:  

   5: textBox1.Text = processBBCNews(antecedent.Result).ToString();

   6:  

   7: int time_stop = System.Environment.TickCount;

   8:  

   9: label1.Text = (time_stop - time_start).ToString();

  10:  

  11: },

  12:  

  13: //As we already know the View or the UI can only be updated from the UI thread,hence 

  14:  

  15: //we are executing the task in the same thread as the Ui thread

  16:  

  17: TaskScheduler.FromCurrentSynchronizationContext()

  18:  

  19: );

  20:  

  21: }

  22:  

All the explanations are given through the comments .I will share my code in the next blog post where we look at the code behind of the “Both” button.

Advertisements

One response to “Asynchronous programming Deep Dive part 1

  1. Pingback: Asynchronous Programming Series « Using Abhik.Mitra.myThoughts;

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s