好的。這是完整的代碼。我試圖重新使用連接設置KeepAlive,但它不起作用。我使用Feedler和Charles查看了Http消息,但我只能看到Connection:關閉響應。C#不能重用Http連接。沒有KeepAlive頭。 HttpWebRequest.KeepAlive = true;
我看到600個TCP連接處於等待狀態,由10個線程打開。每個線程一次運行一個http請求。
還有一堆反應說 - 未經驗證的請求。該服務需要摘要式身份驗證。代碼顯然是靜態的,只需從不同的線程運行相同的請求幾百次...那麼爲什麼有些請求無法被認證? 我
static void GetRest(string rest)
{
int i = Interlocked.Increment(ref counter);
Uri uri = new Uri(rest);
CredentialCache cc = new CredentialCache();
cc.Add(uri, "Digest", new NetworkCredential("zz", "zz"));
ServicePointManager.FindServicePoint(uri).SetTcpKeepAlive(true, 6000000, 100000);
ServicePointManager.FindServicePoint(uri).ConnectionLimit = 5;
while (!stop)
{
HttpWebRequest req = WebRequest.Create(rest) as HttpWebRequest;
req.Credentials = cc;
req.Method = "GET";
req.Timeout = timeout;
req.KeepAlive = true;
try
{
using (HttpWebResponse res = (HttpWebResponse)req.GetResponse())
{
StreamReader sr = new StreamReader(res.GetResponseStream());
string result = sr.ReadToEnd().Substring(0, 20);
int rc = Interlocked.Increment(ref responseCounter);
Console.Write(".");
Thread.Sleep(20);
}
}
catch (Exception ex)
{
Console.WriteLine("EXCEPTION {0}, {1}", i, ex.Message);
Interlocked.Increment(ref badResponseCounter);
}
}
Interlocked.Decrement(ref counter);
}
我不能給太多瞭解您的具體問題,但對於這樣的事情,我肯定會建議把它歸結爲一個「最低工作示例」,然後從那裏建立起來。例如:首先嚐試1個經過驗證的HTTP請求到這個URI。暫時沒有「ServicePointManager」的東西。然後嘗試串聯600個(不平行)。也許在這一點上'ServicePointManager'的東西需要回來。然後嘗試10並行。等等。 – Domenic 2010-07-05 21:40:14
這個問題也似乎與你自己的相關:http://stackoverflow.com/questions/2179626/reuse-a-httpwebrequest – Domenic 2010-07-05 21:41:51
Domenic。謝謝,但在另一個線程的建議說 - 關閉我做的Httpresponse - 我使用它... ServicePoint的東西是必要的。沒有它,整個事情工作x3慢 – 2010-07-05 21:51:48