c# - HttpWebRequest 强制新连接

标签 c# multithreading httpwebrequest system.net.httpwebrequest

我想通过 HttpWebRequest.AddRange(int, int) 使用多个线程从限制传输服务器下载大文件.问题是我的所有线程,但一个都被阻塞在 GetResponse() 上,可能是因为它们想重用第一个线程的连接。我已将请求的 KeepAlive 属性设置为 false,并使用 ServicePointManager.DefaultConnectionLimit = 1000;

增加了并发连接的最大限制

有趣的是,它有时会起作用。如果我使用 2 个线程,它大部分时间都有效,有时使用 3 个线程,但我从未见过它使用 4 个或更多线程。

这是我的代码的一部分,不是很重要的部分被删除了,给出的片段仍然是我代码中的一个连续 block ,尽管有评论,我没有删除中间的任何内容。

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 会很棒

最佳答案

您是否尝试过异步执行此操作?

请引用这个: How to use HttpWebRequest (.NET) asynchronously?

希望对你有帮助

关于c# - HttpWebRequest 强制新连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31999312/

相关文章:

c# - O2Micro 读卡器上 WINSCARD.DLL 方法 SCardTransmit 的未知响应,包含响应长度信息

android - Android 中使用 Canvas 和 SurfaceView 时的 Thread 或 Runnable

python - 为什么gevent比线程使用更多的内存

.net - 为限时许可编写代码

c# - 数字输入用点替换小数逗号

c# - 使用 linq 获取列表项中的日期差异

c# - 参数化查询和 NULL DateTime 值

c++ - 是否可以获取 atomic_int 的底层存储地址?

android - 如何在 webView 的 url 中发送 referer 请求

c# - HttpWebRequest 返回错误 "The underlying connection was closed"