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

前端之家收集整理的这篇文章主要介绍了c# – 从任务中的异步HttpWebRequest调用捕获异常前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我如何在下面的方法中捕获异常?
private static Task<string> MakeAsyncRequest(string url)
    {
        if (!url.Contains("http"))
            url = "http://" + url;

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
        request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
        request.Method = "GET";
        request.KeepAlive = false;
        request.ProtocolVersion = HttpVersion.Version10;

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

        return task.ContinueWith(t => FinishWebRequest(t.Result));

    }

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

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

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

解决方法

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

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

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

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

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

return task.ContinueWith(t =>
{
    if (t.IsFaulted)
    {
        //handle error
        Exception firstException = t.Exception.InnerExceptions.First();
    }
    else
    {
        return FinishWebRequest(t.Result);
    }
});

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

private static async Task<string> MakeAsyncRequest(string url)
{
    if (!url.Contains("http"))
        url = "http://" + url;

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
    request.Accept = "text/html,*/*;q=0.8";
    request.Method = "GET";
    request.KeepAlive = false;
    request.ProtocolVersion = HttpVersion.Version10;

    Task<WebResponse> task = Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse,null);
    WebResponse response = await task;
    return FinishWebRequest(response);
}
原文链接:https://www.f2er.com/csharp/92347.html

猜你在找的C#相关文章