【发布时间】:2018-06-22 06:51:15
【问题描述】:
我目前正在开发一个将大量数据 (~100mb) 写入 .txt 文件的程序。我在 Google 上搜索了一些关于如何优化不同 IO-Streams 的信息,但并没有真正理解以下内容:
- 如何一次打开多个流
- 如果流是默认缓冲的,或者我必须使用 BufferedStream
- 异步流和缓冲流之间的区别是什么
这是我输出的当前状态:
for (int Row = 0; Row < RowCount; Row++)
{
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(@"C:\Calculations\data1.txt", true))
{
file.WriteLine(Time + "\t" + Row + "\t" + Value1[Row]);
}
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(@"C:\Calculations\data2.txt", true))
{
file.WriteLine(Time + "\t" + tRow + "\t" + Value2[Row]);
}
}
我认为这是做什么的:
- 打开数据流到 data1.txt
- 写入 data1.txt
- 关闭和刷新流
- 打开数据流到 data2.txt
- 写入 data2.txt
- 关闭并刷新流
如果我的判断是正确的,那么对于 100mb 的数据来说,这将是大量的打开、关闭和刷新。我很想在开始时打开多个流,在计算时写入所有数据,然后关闭并刷新流。
【问题讨论】:
-
操作系统已经异步写入文件,这是文件系统缓存的一项基本工作。写入内存,缓存管理器懒惰地将其写入磁盘。 100MB 不足以帮助它,实际上由于需要缓冲而变得更糟。
-
为什么不把你的 using 语句移到 for 循环之前呢?
using(StreamWriter file1=new StreamWriter(...), file2 = new StreamWriter(...)) { for(...) { file1.WriteLine(...); file2.WriteLine(...); }}