[英]Making HttpWebRequest calls in parallel with Threading.Tasks in C#
在C#中與Threading.Tasks並行進行HttpWebRequest調用是否存在一些問題(我在Ubuntu中使用Mono進行編譯)? 當我同步向Google發出25個GET請求時,總共大約需要2-3秒。 當我進行異步調用時,需要花費13秒鍾以上的時間。 我的代碼:
using System;
using System.Net;
using System.Diagnostics;
using System.Threading.Tasks;
public class Google
{
public static void Main(string[] args)
{
Stopwatch timer1 = new Stopwatch();
timer1.Start();
for(int i=1; i<=25; i++){
googleit();
}
timer1.Stop();
TimeSpan timeTaken1 = timer1.Elapsed;
Stopwatch timer2 = new Stopwatch();
timer2.Start();
int TaskCount = 25;
var tasks = new Task[TaskCount];
for (var index = 0; index < TaskCount; index++)
{
tasks[index] = Task.Factory.StartNew(googleit);
}
Task.WaitAll(tasks);
timer2.Stop();
TimeSpan timeTaken2 = timer2.Elapsed;
Console.WriteLine("Sync time: ");
Console.WriteLine(timeTaken1);
Console.WriteLine("async time: ");
Console.WriteLine(timeTaken2);
}
private static void googleit(){
Stopwatch timer = new Stopwatch();
timer.Start();
HttpWebRequest request = WebRequest.Create("http://www.google.com") as HttpWebRequest;
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
response.Close();
timer.Stop();
TimeSpan timeTaken = timer.Elapsed;
Console.WriteLine(timeTaken);
}
}
這應該為您提供所需的東西:
public static void SendAsync()
{
int TaskCount = 8;
var tasks = Enumerable.Range(0, TaskCount).Select(p => googleit());
Task.WhenAll(tasks).Wait();
}
private static async Task googleit()
{
HttpWebRequest request = WebRequest.Create("http://www.google.com") as HttpWebRequest;
request.Credentials = CredentialCache.DefaultCredentials;
var response = await request.GetResponseAsync();
response.Close();
}
它將異步發送所有請求,然后等待(阻止)。
在您的代碼中,您只是為每個請求創建一個任務。 因此,例如,如果您有2個內核,並且TPL決定將所有任務拆分到兩個線程之間,則將有兩個線程同步發送請求。 在一個核心上,您將擁有完全同步的執行。 在上面的代碼中,您有一個線程異步發送所有請求,也就是說,它發布了一個請求並繼續發送下一個請求,而無需等待前一個返回。 發送完所有請求之后,它將阻塞線程,直到繼續執行(在您的情況下為'response.Close()')為止。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.