-2

Please tell me, what is the difference between these two methods? Both of whether they will run async? And what will be done in the stream that comes after the words await?

public async Task<ActionResult> RunAsync()
{
   var client = new WebClient();
   await client.DownloadDataAsync(someUri);

   return _jsonDataResult;
}

and

public async Task<ActionResult> RunAsync()
{
   var client = new WebClient();

   await Task.Run(()=> 
   {
      client.DownloadData(someUri);
   });

   return _jsonDataResult;
}

Does it make sense to use 2nd method?

David Pine
  • 23,787
  • 10
  • 79
  • 107
  • 2
    This question might help you - http://stackoverflow.com/questions/18013523/when-correctly-use-task-run-and-when-just-async-await – smoksnes Dec 09 '16 at 12:40
  • 1
    @DavidPine I didn't notice that the question text asked something different than the title. And there are no native APIs, you mean *natively asynchronous APIs*. The question shows a *LOT* of confusion, eg why `await Task.Run` instead of `return Task.Run`? Or even `await client.DownloadDataAsync();` instead of `return client.DownloadAsync()`? – Panagiotis Kanavos Dec 09 '16 at 13:18
  • 1
    Actually, in looking at the source code -- the `WebClient` doesn't even expose the [`.DownloadDataAsync`](https://referencesource.microsoft.com/#System/net/System/Net/webclient.cs,2026) as a `Task` returning method. As such, it cannot be awaited! – David Pine Dec 09 '16 at 13:24
  • `WebClient` follows the recommended pattern of having **TaskAsyn** suffixed methods for TAP because it already had **Task** suffixed methods for EAP. – Paulo Morgado Dec 09 '16 at 13:30

1 Answers1

1

Please tell me, what is the difference between these two methods?

The first one downloads some data asynchronously. The second one downloads some data synchronously (blocking a thread pool thread until the download completes).

Both of whether they will run async?

Well, that depends on your definition of "asynchronous". I would say that the first one is "truly asynchronous" and the second one is "fake asynchronous".

And what will be done in the stream that comes after the words await?

Yeah, not sure what this question even means. The stream is already read at that point.

Does it make sense to use 2nd method?

No, unless you're running into some problem with synchronous execution. For example, DNS lookups can be slow, and they're usually done synchronously even by asynchronous APIs (a design mistake IMO).

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810