This will be the last of our series Asynchronous programming.Now since we have a strong background of tasks,this will be very easy to grasp since from C# 5.0,asynchronous has been heavily simplified to represent closely its synchronous counter part.
We have two new keywords called async and await which we will be using.I will be referring to my previous posts .
Our demo app looks like this .The third column having textblocks for comments
Scenario 1 : Heavy work without using await .
So lets see the code for the No Await button
AsyncDownloadFeed downloads news off the BBC website and also runs a synchronous piece of loop
Lets look at the code behind AsyncDownloadFeed.
yes I know I have used await here but bear with me.Treat this function as a blackbox.Next is the synchronous loop
Click on the No await button and we will see, the difference between start time and end time is only 20 miliseconds apart.As expected,the textblocks populates even before the function AsyncDownloadFeed is completed.
If we wait a few seconds, we will finally see the result.
We already know this phenomenon as its not waiting for the function call to finish.
1.Why does it not wait for the function? It should have been synchronously waiting.?
Answer: Using the “async” keyword isnt the what causing the asynchronous behaviour.The async keyword single handedly cannot be used to transform any synchronous code into non asynchronous one.Async keyword just informs the compiler that there may be code which would need to be run asynchronously. So what is the cause ? Lets examine the AsyncDownloadFeed function by providing two outputs.
Task<WebResponse> response = WebRequestObject.GetResponseAsync(); is familiar since we already are acquainted with TPL.
resp = await response; is the place where the magic occurs.This tells the compiler that it needs to wait for the response but in such a way,so that it does not block the UI.But this is not similar to “wait” as not only does it not block the UI,the compiler moves on to the next statement .Which means,the insaneSynchronousLongLoop() runs even before the webresponse is returned.Moreover in the insaneSynchronousLongLoop does not block the UI since its running on a different thread.
Another thing is ,we can manipulate the UI within the insaneSynchronousLongLoop () since the compiler takes care of that updating the UI only when the threads return to the main UI.