I use the following code to get the endpoint and write it to the cache:
public async Task UpdateCacheFromHttp(string Uri)
{
if (string.IsNullOrEmpty(Uri))
return;
var httpClient = new HttpClient();
var response = await httpClient.GetAsync(Uri);
if ((response != null) && (response.IsSuccessStatusCode))
{
var responseStream = await response.Content.ReadAsStreamAsync();
WriteToCache(responseStream);
}
}
The code works in IIS.
If the endpoint cannot be reached, I expect GetAsync to throw an exception. Even with Try-Catch it never fails. GetAsync never returns (I tried a 5 second timeout on HttpClient, haven't returned yet).
This throws an exception:
public Task UpdateCacheFromHttp(string Uri)
{
var updateCacheTask = Task.Factory.StartNew(new Action(() =>
{
if (string.IsNullOrEmpty(Uri))
return;
var httpClient = new HttpClient();
var response = httpClient.GetAsync(Uri).Result;
if (response.IsSuccessStatusCode)
{
var responseStream = response.Content.ReadAsStreamAsync().Result;
WriteToCache(responseStream);
}
}));
return updateCacheTask;
}
I get the expected "Unable to connect to the remote server."
I suspect this has something to do with the code running in IIS, but why? How do I get it to throw an exception correctly without having to start a new task?
source
share