0

我有一個基於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.ForeachTPL 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以獲得更好的性能嗎?

編輯:我的目標是儘可能快地執行所有調用。

+0

爲什麼不使用[GetResponseAsync](https://msdn.microsoft.com/en-us/library/system.net.webrequest.getresponseasync(v = vs.110).aspx)? –

+0

@JeroenHeier我真的很驚訝,我錯過了這一點。真的是我生命中最尷尬的時刻之一..我一定很累。請張貼您的答覆作爲答案。 – Hubbs

回答

0

您可以使用GetResponseAsync加速解決方案。另請參閱this Micorsoft演練,其中深入解釋了兩種方法(同步和異步)。