Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

webrequest的问题 #117

Open
yangbocheng opened this issue Jan 10, 2023 · 4 comments
Open

webrequest的问题 #117

yangbocheng opened this issue Jan 10, 2023 · 4 comments
Labels
enhancement New feature or request

Comments

@yangbocheng
Copy link

项目中多处使用到了webrequest
我之前看到资料说webrequest底层现在自动使用了Httpclient, 因此是否可能使用httpclient后资源无法及时释放的问题。这点我也不确定。
是否考虑用现成的比如restsharp库

image

@kklldog
Copy link
Collaborator

kklldog commented Jan 11, 2023

webrequest的用法我用了好几年了,但是底层实现被微软替换没替换我不知道了。
有空我调研下到底哪个才是现在.net6下发送 http 的最佳实践。

@yangbocheng
Copy link
Author

yangbocheng commented Jan 11, 2023

我按如下进行了测试。用factory创建的就不会有问题。直接用using httpclient的可能在1 、2 万请求后就会爆出耗尽套接字

builder.Services.AddHttpClient();
var app = builder.Build();

{
    var urls = new List<string>() { "http://localhost:17080", "http://localhost:17081" };
    
    for (int i = 0; i < 100000; ++i)
    {
        using (var scope = app.Services.CreateScope())
        {
            var factory = scope.ServiceProvider.GetService<IHttpClientFactory>();
            var c = factory.CreateClient();
            var url = urls[i % 2];
            var u = $"{url}?id={new Random().Next(100000)}";
            var r = await c.GetAsync(u);
            var content = await r.Content.ReadAsStringAsync();
            Console.WriteLine($"{i}次 返回{content}");
        }
        //using (var c = new HttpClient())
        //{
        //    var url = urls[i % 2];
        //    var u = $"{url}?id={new Random().Next(100000)}";
        //    var r = await c.GetAsync(u);
        //    var content = await r.Content.ReadAsStringAsync();
        //    Console.WriteLine($"第{i}次 返回{content}");
        //}
    }
}

@kklldog
Copy link
Collaborator

kklldog commented Jan 12, 2023

确实,微软已经不推荐直接使用 httpwebrequest 这个类了,推荐使用 httpclient 来代替。
https://learn.microsoft.com/en-us/dotnet/api/system.net.httpwebrequest?view=net-7.0
有空我会改一下使用 IHttpClientFactory 来实现。
有个有趣的事:
https://github.com/dotnet/runtime/blob/main/src/libraries/System.Net.Requests/src/System/Net/HttpWebRequest.cs#L1146
在最新的 .net 源码上这部分的代码已经改进了,貌似在使用 cache 来避免大量创建 httpclient ,不会后面的版本 HttpWebRequest 又能用了吧,哈哈。

@yangbocheng
Copy link
Author

微软反复横跳,哈哈

@kklldog kklldog added the enhancement New feature or request label Oct 6, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants