[C#]平行處理網路傳輸時因連線數不足發生連線Timeout的解決方案
namespace ConsoleApplication15
{
class Program
{
public static string url = “https://www.google.com/images/srpr/logo3w.png";
private static List<WaitHandle> finished = new List<WaitHandle>();
public static void Main()
{
ServicePointManager.DefaultConnectionLimit = 200;
finished.Clear();
for (var idx = 0; idx < 5; ++idx )
{
finished.Add(new ManualResetEvent(false));
Download(idx, url);
}
WaitHandle.WaitAll(finished.ToArray());
Console.WriteLine(“Done…”);
}
private static void Download(int idx, string url)
{
var wc = new WebClient();
wc.OpenReadCompleted += wc_OpenReadCompleted;
wc.OpenReadAsync(new Uri(url), idx);
}
private static void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
Console.WriteLine(string.Format("{0}: Download Completed", e.UserState));
var idx = (int)e.UserState;
var manualResetEvent = finished[idx] as ManualResetEvent;
Debug.Assert(manualResetEvent != null, "manualResetEvent != null");
manualResetEvent.Set();
}
}
}