尝试同时发送数百个http请求时,程序抛出SocketException

时间:2019-06-07 17:30:30

标签: c# http

我已经编写了一个API终结点并创建了一个简单的.net核心控制台应用程序,以同时向该API终结点发送多个请求,以测试该API终结点的工作方式

代码如下所示

    static async Task Main(string[] args)
    {

        // ARRANGE

        int request_number = 200;
        Task<HttpResponseMessage>[] tasks = new Task<HttpResponseMessage>[request_number];
        Action[] actions = new Action[request_number];

        for (int i = 0; i < request_number; i++)
        {
            int temp = i;
            actions[temp] = () =>
            {
                tasks[temp] = CallMyAPI();
            };
        }


        // ACT
        Parallel.Invoke(actions);
        await Task.WhenAll(tasks);


        // ASSERT
        string sample1 = await tasks[0].Content.ReadAsStringAsync();
        for (int i = 1; i < request_number; i++)
        {
            string toBeTested = await tasks[i].Content.ReadAsStringAsync();
            if (toBeTested != sample1)
            {
                Console.WriteLine("Wrong! i = " + i);
            }
        }

        Console.WriteLine("finished");

        Console.WriteLine("Press any key to complete...");
        Console.Read();
    }

    static async Task<HttpResponseMessage> CallMyAPI()
    {


        var request = new HttpRequestMessage();
        request.Method = HttpMethod.Post;

        string contentString = "some json string as http body";
        request.Content = new StringContent(contentString, System.Text.Encoding.UTF8, "application/json");

        request.RequestUri = new Uri("http://myAPIendpoint.com");

        HttpResponseMessage response;
        using (HttpClient httpClient = new HttpClient())
        {
            response = await httpClient.SendAsync(request);
        }

        return response;
    }

因此,基本上我一直在尝试通过代码执行的操作是一次发送多个请求,然后等待并记录所有响应。然后,我将它们进行比较以验证它们是否都返回相同的响应。

最初,当我将变量request_number设置为较小的数字(如50、100)时,测试应用程序运行良好。但是,随着request_number上升并达到200左右,它将开始引发如下异常:

Inner Exception 1: IOException: Unable to read data from the transport connection: The I/O operation has been aborted because of either a thread exit or an application request.

Inner Exception 2: SocketException: The I/O operation has been aborted because of either a thread exit or an application request

这种异常应该意味着什么?

1 个答案:

答案 0 :(得分:0)

您的问题是这个

 using (HttpClient httpClient = new HttpClient())
        {..
}

每个都使用一个新的套接字。 使用单个httpclient,例如静态的