加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – HttpClient.GetAsync一次只执行2个请求?

发布时间:2020-12-15 23:41:46 所属栏目:百科 来源:网络整理
导读:为什么HttpClient.GetAsync()/ PostAsync()/ SendAsync()等一次只能调度2个请求? 我通过以下方式测试了这个: 我有一个异步GET方法,在响应之前等待10秒钟没有阻塞. public async Taskstring Get(){ var guid = Guid.NewGuid(); System.Diagnostics.Trace.Wr
为什么HttpClient.GetAsync()/ PostAsync()/ SendAsync()等一次只能调度2个请求?

我通过以下方式测试了这个:

我有一个异步GET方法,在响应之前等待10秒钟没有阻塞.

public async Task<string> Get()
{
    var guid = Guid.NewGuid();
    System.Diagnostics.Trace.WriteLine($"{guid}: {DateTime.Now.ToLongTimeString()}: start");
    await Task.Delay(10000);
    System.Diagnostics.Trace.WriteLine($"{guid}: {DateTime.Now.ToLongTimeString()}: end");
    return "hello";
}

如果我通过刷新多次从Chrome调用端点,我看到它们在我刷新后立即执行,并且我在10秒后收到响应:

39a20541-a2d6-4cd0-99cd-db0987e273e9: 5:32:44 PM: start
8326d829-28a6-48a2-9874-6506b79488af: 5:32:44 PM: start
aecfbb10-266c-46f8-be3b-bfc2fadf0775: 5:32:44 PM: start
78932f53-37a5-4f26-a56f-b3196256e1cf: 5:32:44 PM: start
39a20541-a2d6-4cd0-99cd-db0987e273e9: 5:32:54 PM: end
8326d829-28a6-48a2-9874-6506b79488af: 5:32:54 PM: end
aecfbb10-266c-46f8-be3b-bfc2fadf0775: 5:32:54 PM: end
78932f53-37a5-4f26-a56f-b3196256e1cf: 5:32:54 PM: end

但是如果我在控制台应用程序中使用此代码进行调用:

var client = new HttpClient();
for (var ii = 0; ii < 10; ii++)
{
    client.GetAsync("http://localhost:50621/api/default");
}
Console.ReadKey();

我看到Console.ReadKey();是立即到达,但请求是两个两个执行 – 它发出2个请求,然后等待10秒完成,然后另外2个,另外10秒等,即使所有10个已经被安排.

80546610-c20e-4ff1-b6e5-0fe1688e8803: 5:39:10 PM: start
9bbbb707-9ea7-44da-9d5b-03efc3c4aa47: 5:39:10 PM: start
80546610-c20e-4ff1-b6e5-0fe1688e8803: 5:39:20 PM: end
9bbbb707-9ea7-44da-9d5b-03efc3c4aa47: 5:39:20 PM: end
a146c3ca-a0d2-4588-b60b-156f1febc944: 5:39:20 PM: start
b71bc77f-9bdb-4aa6-936e-c702eb7d49eb: 5:39:20 PM: start
....

那么为什么不立即提出所有要求呢? HttpClient是否对待处理的请求有某种限制?

解决方法

HttpClient以及其他与http相关的类使用服务点进行http连接管理:

The ServicePoint class handles connections to an Internet resource
based on the host information passed in the resource’s Uniform
Resource Identifier (URI). The initial connection to the resource
determines the information that the ServicePoint object maintains,
which is then shared by all subsequent requests to that resource.

ServicePointManager.DefaultConnectionLimit是一个静态属性,它控制ServicePoint对象允许的默认最大并发连接数,默认情况下,此属性的值为2.

这意味着默认情况下,您只能与给定主机建立2个并发连接.要“修复”这个 – 将该数字增加到更大的值,通常是在应用程序启动时的某个地方.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读