c# - 程序在尝试同时发送数百个 http 请求时抛出 SocketException

标签 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 左右,它开始抛出如下所示的异常:

内部异常 1: IOException:无法从传输连接读取数据:由于线程退出或应用程序请求,I/O 操作已中止。

内部异常 2: SocketException:由于线程退出或应用程序请求,I/O 操作已中止

这种异常是什么意思?

最佳答案

你的问题是这样的:

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

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

关于c# - 程序在尝试同时发送数百个 http 请求时抛出 SocketException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56498883/

相关文章:

http - 在基本身份验证 URL 中转义用户名字符

c# - Entity Framework 6 - 使用 ToString 加入时出现 ORA-00932

无效/丢失主机名的 Http 响应代码

java - Last-Modified 与 ETag http

c# - 如何将对象转换为另一个基数为 'higher' 的对象?

http - 如何在不等待的情况下发送请求?

嵌套对象的 RESTful 重新排序

c# - 将文本文件转换为 Excel

c# - foreach 循环与 ForEach 方法 - 区别?

c# - AutoResetEvent.WaitOne 超时与 Thread.Sleep