c# – 从任务中的异步HttpWebRequest调用捕获异常

前端之家收集整理的这篇文章主要介绍了c# – 从任务中的异步HttpWebRequest调用捕获异常前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我如何在下面的方法中捕获异常?
  1. private static Task<string> MakeAsyncRequest(string url)
  2. {
  3. if (!url.Contains("http"))
  4. url = "http://" + url;
  5.  
  6. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  7. request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
  8. request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
  9. request.Method = "GET";
  10. request.KeepAlive = false;
  11. request.ProtocolVersion = HttpVersion.Version10;
  12.  
  13. Task<WebResponse> task = Task.Factory.FromAsync(
  14. request.BeginGetResponse,asyncResult => request.EndGetResponse(asyncResult),(object)null);
  15.  
  16. return task.ContinueWith(t => FinishWebRequest(t.Result));
  17.  
  18. }

我得到404,403错误的具体地点是:

  1. Task<WebResponse> task = Task.Factory.FromAsync(
  2. request.BeginGetResponse,(object)null);

我无法弄清楚如何处理它们

解决方法

您的错误可能发生在您的委托调用request.EndGetResponse(asyncResult)中.

但是您可以使用以下命令创建任务:

  1. Task<WebResponse> task = Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse,request.EndGetResponse,null);

这应该传播任务的任何例外.

您可以在ContinueWith委托中检查错误

  1. return task.ContinueWith(t =>
  2. {
  3. if (t.IsFaulted)
  4. {
  5. //handle error
  6. Exception firstException = t.Exception.InnerExceptions.First();
  7. }
  8. else
  9. {
  10. return FinishWebRequest(t.Result);
  11. }
  12. });

或者,如果您使用的是C#5,则可以使用async / await创建MakeAsyncRequest.这将为您从AggregateException中解除异常:

  1. private static async Task<string> MakeAsyncRequest(string url)
  2. {
  3. if (!url.Contains("http"))
  4. url = "http://" + url;
  5.  
  6. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  7. request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
  8. request.Accept = "text/html,*/*;q=0.8";
  9. request.Method = "GET";
  10. request.KeepAlive = false;
  11. request.ProtocolVersion = HttpVersion.Version10;
  12.  
  13. Task<WebResponse> task = Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse,null);
  14. WebResponse response = await task;
  15. return FinishWebRequest(response);
  16. }

猜你在找的C#相关文章