我有一个基于HTTPS的API,我需要调用很多次。使用HttpWebRequest.Create(uri).GetResponse()需要从50ms到500ms或更多才能执行。为了检查响应时间我实现这样的:C# - HttpWebRequest/GetResponse性能
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不同要求的很多,为了加快这一进程,我决定使用(而不是Parallel.Foreach
)TPL Dataflow Block
,因为Parallel.Foreach
主要用于CPU bound
工作,我正在做的是I/O bound
(还有处理响应,所以也有一些CPU工作)。而当我使用TPL数据流块时,处理250个URL需要7秒的时间来执行,而并行Foreach需要15秒或更长的时间,所以我认为TPL数据流块的使用是正确的。我是如何实现它:
//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
,事情我到目前为止已经试过和它NONE工作:
ServicePointManager.UseNagleAlgorithm = false;
ServicePointManager.Expect100Continue = false;
ServicePointManager.SetTcpKeepAlive(false, 0, 0);
ServicePointManager.DefaultConnectionLimit = 1000;
第二个问题:如果不可能加快GetResponse()
以达到更快的执行速度,有什么办法可以调整TPL Dataflow Block
以获得更好的性能吗?
编辑:我的目标是尽可能快地执行所有调用。
为什么不使用[GetResponseAsync](https://msdn.microsoft.com/en-us/library/system.net.webrequest.getresponseasync(v = vs.110).aspx)? –
@JeroenHeier我真的很惊讶,我错过了这一点。真的是我生命中最尴尬的时刻之一..我一定很累。请张贴您的答复作为答案。 – Hubbs