执行client.SendAsync时出现HttpRequestException

时间:2014-08-08 22:57:17

标签: c# .net asynchronous async-await dotnet-httpclient

突然间,这段通常有效的代码开始抛出HttpRequestException错误。在日志中,我看到请求实际上是在抛出错误之前1分35秒发送的。这可能是超时问题吗?

以下是代码:

private async Task<HttpResponseMessage> RunRequest(HttpRequestMessage request)
{            
    var client = new HttpClient();
    var response = await client.SendAsync(request).ConfigureAwait(false);              
    return response;           
}

这是来电者(可能介于10K到50K之间):

int counter = 0;
var tasks = items.Select(async i =>
{
    if (await RunRequest(CreateRequest(i)))
        counter++
}).ToList();

if (tasks.Any())
{ 
    await Task.WhenAll(tasks);
}

这是错误:

System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The request was aborted: The request was canceled.
        at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
        at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
        --- End of inner exception stack trace ---
        at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
        at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
        at MyClass.<RunRequest>d__c.MoveNext()
        --- End of inner exception stack trace ---
        at MyClass.<RunRequest>d__c.MoveNext()
        --- End of stack trace from previous location where exception was thrown ---
        at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
        at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
        at MyClass.<RunRequest>d__0.MoveNext()

Task.WhenAll可以处理限制吗?

1 个答案:

答案 0 :(得分:0)

如果您的所有请求都在同一个域中,那么您需要将其添加到“Web.config”文件中(默认只有2个):

<configuration>
    <system.net>
        <connectionManagement>
            <add address="*" maxconnection="100" />
        </connectionManagement>
    <system.net>
<configuration>

而且你已经在顺序等待每一个RunRequest,所以实际上没有任何内容在并列中运行 - 并且你的Task.WhenAll应该抛出一个异常,因为你将它归结为{{1} } list而不是HttpResponseMessage列表。

Task未返回RunRequest,那么您如何在bool中使用它?

......这段代码有这么多错误......