我有以下方法:
private static async void SendRequest()
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://google.com");
httpWebRequest.KeepAlive = false;
httpWebRequest.Proxy = null;
httpWebRequest.Timeout = 1;
try
{
await httpWebRequest.GetResponseAsync();
Console.WriteLine("GetResponse Finished");
}
catch (Exception ex)
{
Console.WriteLine("Exception thrown="+ex);
}
}
这会在无法解析名称的情况下抛出异常,但在超时的情况下似乎永远不会抛出异常。如果我将 GetResponse 与不切实际的 1 毫秒超时一起使用,它总是会引发超时异常,但 GetResponseAsync 似乎不会发生这种情况。
知道如何像同步方法一样抛出和处理超时异常吗?
最佳答案
如前所述in the documentation , HttpWebRequest.Timeout
不适用于异步请求。在这种情况下,您必须编写自己的超时代码。
或者您可以升级到 HttpClient
,它会为您完成很多工作。
关于c# - 如何捕获从 HttpWebRequest.GetResponseAsync 抛出的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22401715/