2011-12-06 64 views
3

我知道有些服務器不允許這樣做,但有些服務器支持多個連接。我可以下載部分文件,並在下載最後一部分後將它們合併,因爲我爲每個文件部分使用單獨的後臺工作器...所以速度很慢,並且一次下載一個文件部分。我想要立即開始下載每個文件部分。但我不知道該怎麼做。 告訴我哪種方法更快,以及如何使用它們。如何打開多個連接來下載單個文件?

Backgroundworker 
Threads 
ThreadPool 

感謝您的幫助。

+0

是什麼樣的下載呢? http? –

+0

簡單的文件下載。 –

+1

直接通過Socket,通過FTP,HTTP或其他。這很重要,因爲不是每個協議都可以讓你從某個特定點下載文件。 –

回答

11

如果您正在下載的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 
+0

我已經使用這種方法下載文件塊... HttpWebRequest.AddRange方法(Int32,Int32)...我想在多線程中實現它... –

+1

@ m.qayyum看到我的代碼 –

+0

..謝謝非常。你是真棒:) –

相關問題