繁体   English   中英

C#-HttpWebRequest / GetResponse性能

[英]C# - HttpWebRequest / GetResponse performance

我有一个基于HTTPS的API,需要多次调用。 使用HttpWebRequest.Create(uri).GetResponse()需要50毫秒到500毫秒或更长的时间才能执行。 为了检查响应时间,我像这样实现它:

private void Action()
{
    WebRequest request = HttpWebRequest.Create("https://.....");
    using (WebResponse response = request.GetResponse()) { }
}

然后调用它:

private long getTime()
{
    Stopwatch sw = new Stopwatch();
    sw.Start();
    Action();
    return sw.ElapsedMilliseconds;
}

多个呼叫的输出:

Time: 746 ms
Time: 51 ms
Time: 50 ms
Time: 50 ms
Time: 51 ms
Time: 49 ms
Time: 2417 ms ???
Time: 52 ms
Time: 52 ms
Time: 51 ms
Time: 50 ms
Time: 201 ms
Time: 234 ms
Time: 204 ms
Time: 51 ms
Time: 50 ms
Time: 50 ms
Time: 52 ms
Time: 280 ms
Time: 264 ms

第一个问题:我想知道是否有任何方法可以加快GetResponse的速度,以使其花费的时间尽可能少?

现在..因为我需要使用不同的URL进行很多不同的请求,所以为了加快处理过程,我决定使用TPL Dataflow Block (而不是Parallel.Foreach ),因为Parallel.Foreach主要用于CPU bound工作。 ,而我正在做的是I/O bound (响应也要处理,因此还需要一些CPU工作)。 当我使用TPL Dataflow Block时,执行250个URL的处理最多需要7秒,而Parallel Foreach则需要15秒或更长时间,所以我很肯定使用TPL Dataflow Block是正确的方法。 我是如何实现的:

//CALL:
var block = new ActionBlock<string>(uri => Action(uri), new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 200 });
foreach (var URL in urlArray)
{
    block.Post(URL);
}
block.Complete();
await block.Completion;

//Action(uri):
private void Action(string uri)
{
    WebRequest request = HttpWebRequest.Create(uri);
    using (WebResponse response = request.GetResponse()) { }
}

由于我对7s的执行不满意,因此我尝试调整ServicePointManager来加快速度,到目前为止,我已经尝试过但没有任何效果:

ServicePointManager.UseNagleAlgorithm = false;
ServicePointManager.Expect100Continue = false;
ServicePointManager.SetTcpKeepAlive(false, 0, 0);
ServicePointManager.DefaultConnectionLimit = 1000;

第二个问题:如果无法加快GetResponse()以实现更快的执行速度,是否有任何方法可以调整TPL Dataflow Block使其具有更好的性能?

编辑:我的目标是尽快执行所有调用。

您可以使用GetResponseAsync加快解决方案的速度。 另请参阅 Micorsoft演练,其中详细介绍了这两种方法(同步和异步)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM