System.NetとWinInet

5つのスレッドを用いて50ページをダウンロードした場合の
パフォーマンスを比較してみた。
平均すると、


WinINet 4.140秒
Sysetm.Net 6.109秒


Sysetm.Netを非同期で試しても結果が変わらない。
ずいぶん遅いと思い調べていたら、


ServicePointManager.DefaultConnectionLimitがデフォルト2なので、
これを変更する必要があるらしい。
http://msdn.microsoft.com/library/ja/default.asp?url=/library/ja/jpdndotnet/htm/frame_1.asp


結果 4.512秒



public static string DownloadString(IntPtr inet, string uri, Encoding enc) {
IntPtr req = InternetOpenUrl(
inet, uri, "", -1, /*INTERNET_FLAG_RELOAD*/0x80000000, IntPtr.Zero);

byte[] bytes = new byte[4096];
string html = string.Empty;
using (MemoryStream ms=new MemoryStream()) {
for (;;) {
uint len = 0;
if (!InternetReadFile(req, bytes, 4096, ref len)) break;
if (len == 0) break;
ms.Write(bytes, 0, (int)len);
}
ms.Position = 0;

using (StreamReader sr=new StreamReader(ms, enc)) {
html = sr.ReadToEnd();
}
}
InternetCloseHandle(req);
return html;
}

public static string DownloadString(string uri, Encoding enc) {
HttpWebRequest req = WebRequest.Create(address) as HttpWebRequest;
req.Encoding = enc;
HttpWebResponse res = req.GetResponse() as HttpWebResponse;
using (StreamReader sr=new StreamReader(res.GetResponseStream(), enc)) { return sr.ReadToEnd();
}
}