6

I am working on an asp.net mvc5 web application, and i am not sure what are the differences between using DownloadStringTaskAsync() & usingDownloadStringAsync() . for example if i have the following webclient :-

 using (WebClient wc = new WebClient())
 {
     string url = currentURL + "home/scanserver?tokenfromtms=" + "12345" + "&FQDN=allscan" ;
     var json = await wc.DownloadStringTaskAsync(url);
     TempData["messagePartial"] = string.Format("Scan has been completed. Scan reported generated");                 
 }

will there be any differences if i chnage DownloadStringTaskAsync(url); to DownloadStringAsync(url); ??

2 Answers 2

12

WebClient.DownloadStringAsync is using the older event-based asynchronous pattern (EAP).

WebClient.DownloadStringTaskAsync is using the newer task-based asynchronous pattern (TAP).

Since your code is already using async/await, I recommend you stick with the TAP method. TAP code is more maintainable than EAP code.

You could also go another step further and consider using HttpClient instead of WebClient. The odd naming in WebClient is due to it supporting both synchronous and EAP, and then later updated to include TAP. In contrast, HttpClient is a newer type that was based on TAP right from the beginning, so its API is cleaner.

Sign up to request clarification or add additional context in comments.

8 Comments

thanks for the reply. but in both cases the iis will wait to receive the string (download the string) before continue execution ? is this correct??. for example in the action method (i wrote in my original question) i will never end up reaching " TempData["messagePartial"] = string.Format("Scan has been completed. Scan reported generated");" line unless the webclient finishes execution (the strinf is fully downloaded)... either using "downloadstringasync" or using "downloadstringtaskasync" is this correct ?
Yes, this is how async works. I encourage you to check out the post I wrote that gives a general overview of how async works and does a little myth-busting about things a lot of people think it does that it doesn't. cpratt.co/async-not-faster
@johnG: The await will pause your current method until the string is downloaded. The EAP version (DownloadStringAsync) cannot be awaited, so your method continues executing immediately while the download is in progress, and the web client notifies you of the download completion via DownloadStringCompleted. Note that the await code is much easier to write and maintain than event-handling code.
@johnG: I'm not sure why the hint isn't showing up. You certainly should use await with DownloadStringTaskAsync, so I'd expect VS to pick up on that...
@johnG: You can wrap the EAP members inside a TAP wrapper, and await that task. But that would be pointless, because DownloadStringTaskAsync already does that.
|
5

The DownloadStringTaskAsync and DownloadStringAsync documentation do a pretty good job of highlighting both similarities and differences.

They both are non-blocking, asynchronous methods. However, DownloadStringAsync has a return signature of void and requires you to listen to the DownloadStringCompleted event to obtain your results from Result, whereas the DownloadStringTaskAsync method returns a Task<string>.

The latter is useful if you have parallel asynchronous operations that you need to await before continuing or if you want to call ContinueWith on the operation once it's completed. In addition, with the latter you'll also need to retrieve the result from the task once the task is in a completed state which can be unwrapped with await.

Finally, DownloadStringAsync requires a URI whereas DownloadStringTaskAsync will accept a string.

For ease of use, DownloadStringTaskAsync will probably work just fine, provided that you've placed it in an async method as follows:

void Main()
{
    using (WebClient wc = new WebClient())
    {
        var json = GetGoogleFromTask(wc);                
        json.Dump();
    }
}

public async Task<string> GetGoogleFromTask(WebClient wc)
{
    string url = "http://www.google.com" ;
    var json = await wc.DownloadStringTaskAsync(url);
    return json;
}

Alternatively, you can also return just the Task so that you can continue other operations without needing an async method that awaits the return:

void Main()
{
    using (WebClient wc = new WebClient())
    {
        var json = GetGoogleFromTask(wc);                
        json.Dump();
    }
}

public Task<string> GetGoogleFromTask(WebClient wc)
{
    string url = "http://www.google.com" ;
    var json = wc.DownloadStringTaskAsync(url);
    return json;
}

8 Comments

not sure i got your point so what type of task "DownloadStringTaskAsync" will return.for example if i am calling a web service that will return a json ,, so how i can work with the return json object as a task ? sorry for asking many questions !!
@johnG I've clarified my answer since DownloadStringAsync's behavior wasn't quite what I was expected. I've also added examples for how to use DownloadStringTaskAsync.
Simplistically, whenever you see *Async and *TaskAsync versions of a method, that means that the *Async version predates the introduction of async-await in C#, and used an evented pattern to achieve a similar effect. *TaskAsync methods were added after async-await and utilize async-await. The previous methods remain for backwards-compatibility.
@ChrisPratt so that why i do not have to explicitly write "await" when using DownloadStringTaskAsync ?? and if i explicitly write "await" will it have any deferences ?
You never have to use await. There's times where you might actually want to interact with the Task<T> object. The await keyword is just syntactic sugar that automatically unwraps the task response. It's functionally the same as just doing MyAsyncTask().Result (though there's some exception handling rolled in that you wouldn't have just hitting the Result property).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.