C# 如何打开多个连接以下载单个文件?

C# 如何打开多个连接以下载单个文件?,c#,multithreading,backgroundworker,threadpool,C#,Multithreading,Backgroundworker,Threadpool,我知道有些服务器不允许这样做,但有些服务器确实支持多个连接。我能够下载文件的一部分,并结合他们下载后的最后一部分,因为我使用单独的背景工人为每个文件部分…所以它是缓慢的,它下载一个文件部分的时间。我想立即开始下载每个文件部分。但我不知道怎么做。 告诉我哪种方法更快,以及如何使用它们 Backgroundworker Threads ThreadPool 谢谢您的帮助。如果您正在以HTTP下载文件, 您可以使用以下方法: 因此,您必须将文件拆分为多个临时文件,然后合并它们 但您必须确保在服务器

我知道有些服务器不允许这样做,但有些服务器确实支持多个连接。我能够下载文件的一部分,并结合他们下载后的最后一部分,因为我使用单独的背景工人为每个文件部分…所以它是缓慢的,它下载一个文件部分的时间。我想立即开始下载每个文件部分。但我不知道怎么做。 告诉我哪种方法更快,以及如何使用它们

Backgroundworker
Threads
ThreadPool

谢谢您的帮助。

如果您正在以HTTP下载文件, 您可以使用以下方法:

因此,您必须将文件拆分为多个临时文件,然后合并它们

但您必须确保在服务器端启用了此功能(我不知道默认情况下是否启用)

正如一些人所说,您将提高性能,这就是免费下载管理器如此有用的原因:它可以同时下载文件的多个部分

要使用多线程执行此操作,请执行以下操作:

class FileDownloader{
int Start;
int Count;
string PathTemp;
string Url;
FileDownloader(url,start,count){
url = Url;
Start =start;
Count = count;
PathTemp = Path.GetTempFileName()
}
void DoDownload(){
//do your thing with stream and request and save it to PathTemp
}
}
以下是初始化下载程序列表的代码:

List<FileDownloader> filewonloadersList = new ListFileDownloader>();
System.Net.WebRequest req = System.Net.HttpWebRequest.Create("http://stackoverflow.com/robots.txt");
req.Method = "HEAD";
System.Net.WebResponse resp = req.GetResponse();
int responseLength = int.Parse(resp.Headers.Get("Content-Length"));
for(int i = 0;i<response.Length;i = i + 1024){
filewonloadersList.Add(new FileDownloader("http://stackoverflow.com/robots.txt",i,1024));
}
List filewonloadersList=newlistfiledownloader>();
System.Net.WebRequest req=System.Net.HttpWebRequest.Create(“http://stackoverflow.com/robots.txt");
请求方法=“头”;
System.Net.WebResponse resp=req.GetResponse();
int responseLength=int.Parse(resp.Headers.Get(“内容长度”);

对于(int i=0;i它是什么类型的下载?http?通过套接字、FTP、http或其他方式直接下载。这很重要,因为不是每个协议都允许您从某个点下载文件。我只想从http协议下载。我已经使用此方法分块下载文件…HttpWebRequest.AddRange方法(Int32,Int32)…我想在多线程中实现它…非常感谢。你太棒了:)我无法在列表中初始化filedownloader…请帮助
List<Thread> threadList = new List<Thread>();
foreach(FileDownloader aFildeDownloader in filewonloadersList)
{
    Thread aThread = new Thread(aFildeDownloader.DoDownload) //this method will be called when the thread starts
    threadList.Add(aThread);
    aThread.Start();
}


foreach(Thread aThread in threadList)
{
    aThread.Join();//will wait until the thread is finished
}
//all the downloader finished their work now you can go through your downloader list and concatenante the temps files