簡體   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