我使用分段http下載使用範圍(HttpWebRequest.AddRanges())分割文件的部分,然後加入所有部分。如果一個文件是100字節,我將它分成4部分(0-24,25-49,50-74,75-99),並且我調用四次DownloadPart函數。 使用異步編程模型(BeginRead/EndRead)下載每個部分。當所有的部件都完成我加入他們的行列,第1部分第2部分+ + ...分段FileStream寫入
public void DowloadPart(HttpWebResponse httpResp)
{
Stream httpStm = httpResp.GetResponseStream();
Stream fileStm = new FileStream("myFile.part1", FileMode.Append, FileAccess.Write);
byte[] buff = new byte[1024 * 16];
AsyncCallback callback = null;
callback = ar =>
{
int bytesRead = httpStm.EndRead(ar);
fileStm.Write(buff, 0, bytesRead);
if(bytesRead == 0)
return;
httpStm.BeginRead(buff, 0, buff.Length, callback, null);
};
httpStm.BeginRead(buff, 0, buff.Length, callback, null);
}
我想更換零件直接寫入文件的加盟。由於所有「DownloadPart」都在不同的線程中運行,在不同線程的不同位置同時寫入FileStream的最佳方式是什麼?
請不要只問我們爲你解決問題。告訴我們你是如何試圖自己解決問題的,然後向我們展示結果是什麼,並告訴我們爲什麼你覺得它不起作用。請參閱「[您嘗試過什麼?](http://whathaveyoutried.com/)」,以獲得一篇您最近需要閱讀的優秀文章。 –
@JohnSaunders我填充了「myFile」(不使用部分),並且我得到了System.IO.IOExeption(另一個線程可能導致操作系統文件句柄的位置發生意外更改) – albert
不知道爲什麼會發生這種情況一個單一的線程。 –