我知道有些服务器不允许这样做,但有些服务器支持多连接。我可以分部分下载文件并在下载最后一部分后将它们组合起来,因为我为每个文件部分使用单独的后台工作程序......所以它很慢并且一次下载一个文件部分。我想立即开始下载每个文件部分。但我不知道该怎么做。 告诉我哪种方法更快以及如何使用它们。
Backgroundworker
Threads
ThreadPool
感谢您的帮助。
最佳答案
如果您使用 HTTP 下载文件, 你可以使用这个方法:
http://msdn.microsoft.com/en-us/library/7fy67z6d.aspx
因此您必须将文件拆分为多个临时文件,然后合并它们。
但是你必须确保在服务器端启用了这个功能(我不知道它是否默认)。
正如一些人所说,您将获得性能提升,这就是免费下载管理器如此有用的原因:它可以同时下载文件的多个部分。
用多线程来做到这一点:
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));
}
你的程序将在一个列表中初始化 X 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
关于c# - 如何打开多个连接来下载单个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8397060/