WebClient vs. HttpClient - Async request
I have this very simple WebApi method:
[HttpGet]
public IHttpActionResult Foo()
{
Thread.Sleep(3000);
return Ok("Bar");
}
And I have two methods in a console application that call it:
async Task UsingWebClient()
{
Task<string> task = new WebClient().DownloadStringTaskAsync (new Uri ("http://localhost.fiddler:63710/api/producttype/Foo"));
Console.WriteLine("WebClient - Before calling wait");
string result = await task;
Console.WriteLine("WebClient - After calling wait");
}
async Task UsingHttpClient()
{
Task<string> task = new HttpClient().GetStringAsync (new Uri ("http://localhost.fiddler:63710/api/producttype/Foo"));
Console.WriteLine("HttpClient - Before calling wait");
string result = await task;
Console.WriteLine("HttpClient - After calling wait");
}
And I am calling these methods from LinqPad like this:
async Task Main()
{
await UsingWebClient();
await UsingHttpClient();
}
I was tracking traffic using Fiddler and I noticed that:
- when using WebClient, the web api request is executed immediately and then execution continues to Console.WriteLine ("WebClient - Before call wait");
- when using HttpClient, the request to the web api is not executed until the call is waiting for the task;
I am trying to understand why the request is not immediately executed when using the HttpClient. Can anyone point me in the right direction?
This is not a duplicate question. I'm not looking for a reason to pick one option over the other - I'll be using HttpClient. I would like to know specifically why the request is generated at a later stage when using the HttpClient.
Thanks David
source to share
Since both requests are asynchronous, neither should delay the execution of the current thread (significantly).
It is possible, however, that one of them can send a request before the current thread reaches the next line, and the other cannot.
Synchronization issues like this can occur in asynchronous / concurrent environments, and they don't have to worry about as long as you don't separate logically sequential operations.
source to share