【发布时间】:2013-10-17 10:22:21
【问题描述】:
我使用分段 http 下载,使用范围 (HttpWebRequest.AddRanges()) 将文件分成几部分,然后加入所有部分。如果一个文件是 100 字节,我将它分成 4 个部分(0-24、25-49、50-74、75-99)并调用四次 DownloadPart 函数。 每个部分都使用异步编程模型(BeginRead/EndRead)下载。当所有部分都完成后,我加入他们,part1+ part2+ ...
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 的最佳方法是什么?
【问题讨论】:
-
请不要只要求我们为您解决问题。向我们展示您如何尝试自己解决问题,然后向我们确切地展示结果是什么,并告诉我们您为什么觉得它不起作用。请参阅“What Have You Tried?”了解您真正需要阅读的优秀文章。
-
@JohnSaunders 我填写了“myFile”(不使用部件)并得到了 System.IO.IOExeption(另一个线程可能导致操作系统文件句柄的位置发生意外变化)
-
不清楚为什么会在一个线程上发生。
-
我在直接写作中没有使用单线程(正如我在问题中所说)
-
那么肯定,异常很明显:让每个线程使用单独的
FileStream
标签: .net multithreading asynchronous .net-2.0