制限付き転送サーバーから複数のスレッドを使用して大きなファイルをダウンロードしたいHttpWebRequest.AddRange(int, int)
. 問題は、おそらく最初のスレッドの接続を再利用したいため、1 つを除くすべてのスレッドが GetResponse() でブロックされることです。リクエストの KeepAlive プロパティを false に設定し、同時接続の最大制限を増やしましたServicePointManager.DefaultConnectionLimit = 1000;
面白いことに、うまくいくこともあります。ほとんどの場合、2 つのスレッドを使用すると機能しますが、3 つを使用することもあり、4 つ以上のスレッドで機能するのを見たことはありません。
これは私のコードの一部であり、それほど重要ではない部分は削除されていますが、指定されたスニペットはコード内の連続したブロックであり、コメントにもかかわらずその間に何も削除していません。
for (int i=0; i < threadpool; i++)
{
pool[i] = new Thread(new ParameterizedThreadStart((object id) =>
{
int myId = (int)(id);
Console.WriteLine("StartThread " + myId);
byte[] buffer = new byte[chunksize];
while (currentChunk < chunks)
{
int myJob = -1;
HttpWebResponse response = null;
lock (currentChunkLock)
{
myJob = currentChunk++;
}
Console.WriteLine(myId + " GOT JOB " + myJob);
HttpWebRequest request = MakeRangedRequest(url, myJob * chunksize, chunksize);
Console.WriteLine(myId + " MADE REQUEST " + myJob);
response = (HttpWebResponse)request.GetResponse();
//They get all stuck here
Console.WriteLine(myId + " GOT RESPONSE " + myJob);
int totalCount = 0;
int targetCount = (myJob + 1 == chunks) ? lastChunkSize : chunksize;
Thread.Sleep(1);
while (totalCount < targetCount)
{
//The only thread that passes is stuck here, it won't allow other threads to continue.
int left = targetCount-totalCount;
int count = response.GetResponseStream().Read(buffer, totalCount, left > 1024 ? 1024 : left);
totalCount += count;
totalBytesSoFar += count;
Console.WriteLine("READING " + myId + "/" + totalCount);
Thread.Sleep(1);
}
response.Close();
Console.WriteLine(myId + " READ BUFFER " + myJob);
lock (file)
{
file.Seek(myJob * chunksize, SeekOrigin.Begin);
file.Write(buffer, 0, chunksize);
file.Flush();
}
Console.WriteLine(myId + " WRITE FILE " + myJob);
Console.WriteLine("Current chunk: " + myJob + "/" + chunks + "\r");
Console.WriteLine("Thread " + myId);
Thread.Sleep(1);
}
Console.WriteLine("Thread " + myId + " out.");
lock (threadsDonePool)
{
threadsDone++;
if (threadsDone == threadpool)
{
file.Close();
Console.WriteLine("File Closed.");
}
}
}));
pool[i].Start(i);
}
MakeRangedRequest 関数は次のとおりです。
static HttpWebRequest MakeRangedRequest(string url, int from, int size)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AddRange(from, from + size);
request.KeepAlive = false;
return request;
}
TCPクラスを使用してこれをすべて行う必要がありますか? HttpWebRequest に固執するのは素晴らしいことです