I was reading about asynchronous function calls on http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx?cs-save-lang=1&cs-lang=csharp.
At the first example, they do this, which I get:
Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com"); // You can do work here that doesn't rely on the string from GetStringAsync. DoIndependentWork(); string urlContents = await getStringTask;
But then they explain that if there's not any work to be done in the mean time, you can just do it like this:
string urlContents = await client.GetStringAsync();
From what I understand, the await
keyword will suspend the code flow until the function returns. So how is this different from:
string urlContents = client.GetString();
?
In synchronous operations tasks are performed one at a time and only when one is completed, the following is unblocked. In other words, you need to wait for a task to finish to move to the next one. In asynchronous operations, on the other hand, you can move to another task before the previous one finishes.
The async keyword turns a method into an async method, which allows you to use the await keyword in its body. When the await keyword is applied, it suspends the calling method and yields control back to its caller until the awaited task is complete. await can only be used inside an async method.
Await eliminates the use of callbacks in . then() and . catch(). In using async and await, async is prepended when returning a promise, await is prepended when calling a promise.
Asynchronous/non-blocking designs are not necessarily faster, but they can scale better than synchronous/blocking designs under some circumstances. Thus, they can be "faster" when handling high volumes of parallel transactions.
Calling await client.GetStringAsync()
yields the execution to the calling method, which means it won't wait for the method to finish executing, and thus won't block the thread. Once it's done executing in the background, the method will continue from where it stopped.
If you just call client.GetString()
, the thread's execution won't continue until this method finished executing, which will block the thread and may cause the UI to become unresponsive.
Example:
public void MainFunc() { InnerFunc(); Console.WriteLine("InnerFunc finished"); } public void InnerFunc() { // This causes InnerFunc to return execution to MainFunc, // which will display "InnerFunc finished" immediately. string urlContents = await client.GetStringAsync(); // Do stuff with urlContents } public void InnerFunc() { // "InnerFunc finished" will only be displayed when InnerFunc returns, // which may take a while since GetString is a costly call. string urlContents = client.GetString(); // Do stuff with urlContents }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With