如何避免在 .NET Core 中使用 HttpWebRequest 发送并发请求时遇到的性能和稳定性问题?
- 内容介绍
- 文章标签
- 相关推荐
本文共计311个文字,预计阅读时间需要2分钟。
在.NET Framework中,使用HttpWebRequest进行大量并发请求时,需要设置最大连接数。通过ServicePointManager.DefaultConnectionLimit=200;实现。但在.NET Core中,此设置无效,因为Core不使用ServicePointManager来管理连接数,仅使用默认值。
在framework中,大量并发 HttpWebRequest 需要设置一个最大连接数
ServicePointManager.DefaultConnectionLimit = 200;
但是在.net core中却无效,因为core不使用ServicePointManager 管理连接数,在core中只有使用HttpClient,HttpCilentFactory来管理连接数,如果在core中使用ServicePointManager 不但不起作用,并且大量并发使用HttpWebRequest 会导致 IIS 直接假死,所以在core中,只能使用HttpClient 和 HttpCilentFactory这一条路可走
在Core中的StartUp注册一个HttpClient的名字
public void ConfigureServices(IServiceCollection services) { services.AddHttpClient("HttpClientFactoryDemo"); }
然后在Controller中创建
using System; using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using System.Web; using Microsoft.AspNetCore.Mvc; namespace HttpClientFactoryDemo.Controllers { [Route("api/[controller]")] [ApiController] public class ValuesController : ControllerBase { private readonly IHttpClientFactory _spay.fuiou.com/commonQuery"), Method = HttpMethod.Post, Content = new ByteArrayContent(postBody), }; request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); return Ok(await client.SendAsync(request)); } } }
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对易盾网络的支持。
本文共计311个文字,预计阅读时间需要2分钟。
在.NET Framework中,使用HttpWebRequest进行大量并发请求时,需要设置最大连接数。通过ServicePointManager.DefaultConnectionLimit=200;实现。但在.NET Core中,此设置无效,因为Core不使用ServicePointManager来管理连接数,仅使用默认值。
在framework中,大量并发 HttpWebRequest 需要设置一个最大连接数
ServicePointManager.DefaultConnectionLimit = 200;
但是在.net core中却无效,因为core不使用ServicePointManager 管理连接数,在core中只有使用HttpClient,HttpCilentFactory来管理连接数,如果在core中使用ServicePointManager 不但不起作用,并且大量并发使用HttpWebRequest 会导致 IIS 直接假死,所以在core中,只能使用HttpClient 和 HttpCilentFactory这一条路可走
在Core中的StartUp注册一个HttpClient的名字
public void ConfigureServices(IServiceCollection services) { services.AddHttpClient("HttpClientFactoryDemo"); }
然后在Controller中创建
using System; using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using System.Web; using Microsoft.AspNetCore.Mvc; namespace HttpClientFactoryDemo.Controllers { [Route("api/[controller]")] [ApiController] public class ValuesController : ControllerBase { private readonly IHttpClientFactory _spay.fuiou.com/commonQuery"), Method = HttpMethod.Post, Content = new ByteArrayContent(postBody), }; request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); return Ok(await client.SendAsync(request)); } } }
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对易盾网络的支持。

