HTT prequestException做client.SendAsync时prequestException、HTT、SendAsync、client

2023-09-03 17:36:57 作者:亡城孤影

突然间,这片code,它通常工作开始抛型Htt prequestException错误。在日志中,我看到,请求实际发送1分35秒的错误被抛出前。难道是一个超时问题?

All of a sudden, this piece of code that usually works started throwing HttpRequestException errors. In the logs, I see that the request was actually sent 1 minute and 35 seconds before the error was thrown. Could it be a timeout issue?

下面是code:

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

下面是调用者(有可能的10K到50K项):

Here is the caller (there could between 10K to 50K items):

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可以处理?

Is there a limit that Task.WhenAll can handle?

推荐答案

如果您所有的请求都在同一个域中,那么你需要添加到你的web.config文件(默认情况下只有2):

If all your requests are to the same domain, then you need to add this to your "Web.config" file (default is just 2):

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

和你在每一个 RunRequest 反过来,连续,所以没有什么实际上是在paralell运行已经等候 - 和你的 Task.WhenAll 应该因为你得到安宁它的Htt presponseMessage 列表,而不是抛出一个异常工作列表。

And you are already awaiting on every single RunRequest in turn, serially, so nothing is actually run in paralell - and your Task.WhenAll should throw an exception since you are givin it a HttpResponseMessage list instead of a Task list.

RunRequest 不返回布尔,那么你如何使用它在如果

RunRequest does not return a bool, so how are you using it in an if?

...还有就是这么多毛病此code ...

...there is just so much wrong with this code...