[英]How to catch exceptions thrown from HttpWebRequest.GetResponseAsync?
I have the following method:我有以下方法:
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);
}
}
This throws an exception in case of failure to resolve name, but it never seems to throw an exception in case of timeout.这会在解析名称失败的情况下引发异常,但在超时的情况下似乎永远不会引发异常。 If I use GetResponse with the unrealistic timeout of 1 ms, it always throws an timeout exception, but this doesn't seem to happen with GetResponseAsync.如果我将 GetResponse 与 1 ms 的不切实际的超时一起使用,它总是会引发超时异常,但 GetResponseAsync 似乎不会发生这种情况。
Any idea how I can get Timeout exceptions to be thrown and handled like the synchronous method ?知道如何像同步方法一样抛出和处理超时异常吗?
As noted in the documentation , HttpWebRequest.Timeout
does not apply to asynchronous requests.如文档中所述, HttpWebRequest.Timeout
不适用于异步请求。 You have to write your own timeout code in that case.在这种情况下,您必须编写自己的超时代码。
Or you could upgrade to HttpClient
, which does a lot of that work for you.或者您可以升级到HttpClient
,它可以为您完成很多工作。
Use Wait() for async method to complete.使用 Wait() 来完成异步方法。 Change void to Task in SendRequest()在 SendRequest() 中将 void 更改为 Task
static void Main()
{
SendRequest().Wait()
}
private static async **Task** 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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.