I have this very simple WebApi method:
[HttpGet]
public IHttpActionResult Foo()
{
Thread.Sleep(3000);
return Ok("Bar");
}
And I have these 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 monitoring the traffic using Fiddler and I noticed that:
- when using WebClient the request to the web api is made immediately and then execution continues to Console.WriteLine("WebClient - Before calling wait");
- when using HttpClient the request to the web api is not made until the call to await task;
I'm trying to understand why the request is not made immediately when using HttpClient. Can anyone point me in the right direction?
This is not a duplicate question. I'm not looking for reasons to choose one option over the other - I'll use HttpClient. I would like to know specifically why the request is created at a later stage when using HttpClient.
Thanks, David