is easy to invoke Asynchronous methods in VS 2012 RC using “async”
To use “await”
in method you have to modified your method with “async”
asynchronous methods instead of synchronous methods can provide
benefits. Asynchronous makes UI applications more responsive because
the UI thread that launches that operation can perform other work.
Asynchronous also improves the scalability of server-based
application by reducing the need for threads.
work flow in asynchronous programming is very simple as compared with
synchronous programming, when we modify method with “async”
then during method calling control reaches an “await”
in async method, control returns to the caller and progress in the
method is suspended till awaited task completes. When the task is
complete, execution can resume in the method.
this example diagram took from MSDN
numbers in above diagram corresponds to following steps.
event handler calls and awaits the “AccessTheWebAsync”async
“AccessTheWebAsync”creates an HttpClient instance and the calls the GetStringAsnc method to the download the contents of website as a string.
happens in GetStringAsyncthat
suspends its progress. Perhaps it must wait for a website to
download or some other blocking activity. To avoid blocking
control to its caller, “AccessTheWebAsync”.
been awaited yet, “AccessTheWebAsync”
continue with other work that doesn't depend on the final result
That work is represented by a call to the synchronous method
“DoIndependentWork”is a synchronous method that does its work and returns to its caller.
run out of work that it can do without a result from
wants to calculate and return the length of the downloaded string,
but the method can't calculate that value until the method has the
and produces a string result. The string result isn't returned by
the call to GetStringAsync
the way that you might expect. (Remember that the method already
returned a task in step 3.) Instead, the string result is stored in
the task that represents the completion of the method,
The await operator retrieves the result from “getStringTask”.
The assignment statement assigns the retrieved result to
the string result, the method can calculate the length of the
string. Then the work of “AccessTheWebAsync”is
also complete, and the waiting event handler can resume. In the full
example at the end of the topic, you can confirm that the event
handler retrieves and prints the value of the length result.
To better undestand what is actually is asynchronous programming, consider the difference between synchronous and asynchronous behavior.
A synchronous method returns when its work is complete (step 5), but an async method returns a task value when its work is suspended (steps 3 and 6).
When the async method eventually completes its work, the task is marked as completed and the result, if any, is stored in the task.