问题描述
我用下面的code得到一个端点,并将其写入到缓存:
I'm using the following code to get an endpoint and write it to a 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);
}
}
在code在IIS上运行。
The code is running on IIS.
如果端点不能达到我期望GetAsync抛出异常。即使有一个try-catch,它似乎永远不会失败。 GetAsync永远不会返回(我试过在HttpClient的5秒超时,仍然没有返回)。
If the endpoint can't be reached I'd expect GetAsync to throw an exception. Even with a Try-Catch, it never seems to fail. GetAsync never returns (I tried a 5 second timeout on the HttpClient, still didn't return).
这确实抛出一个异常:
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".
我怀疑它是与IIS中的code运行,但为什么呢?我如何让它正常抛出异常,而无需启动一个新的任务?
I suspect it has something to do with the code running in IIS, but why? How do I get it to properly throw the exception without the need to start a new task?
推荐答案
我的直觉告诉我,你叫等待
或结果
进一步您的调用堆栈。
My intuition tells me that you're calling Wait
or Result
further up your call stack.
如果这是正确的,那么你就造成了僵局,为的解释。
If that is correct, then you're causing a deadlock, as I explain on my blog.
这篇关于在GetAsync使用的await时的HttpClient没有引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!