询问者
文件写入优化

问题
-
foreach (var c in input.GetConsumingEnumerable()) { using (StreamWriter outputFile = new StreamWriter("zs5", true)) { outputFile.WriteLineAsync(c.ToString()); } }
这段代码每次都需要重新打开文件写入,影响效率,
如果写成这样
using (StreamWriter outputFile = new StreamWriter("zs5", true)) {
foreach (var c in input.GetConsumingEnumerable()) { outputFile.WriteLineAsync(c.ToString()); } }
文件写一会,就不在往里面写了,请问如何优化啊?
please verify my account
全部回复
-
Hi,
欢迎在MSDN论坛发帖。
在程序不再向文件里面写数据的时候,你有debug你的代码了吗? 或者使用try catch 语句来检查一下,是不是有什么异常信息抛出来。
你可以着重检查 InvalidOperationException 和ObjectDisposedException 异常信息。
因为你使用的是异步写入数据,我觉得你是不是应该加一下 await 语句。请参考下面代码:
static async void WriteCharacters() { using (StreamWriter writer = File.CreateText("newfile.txt")) { await writer.WriteLineAsync("First line of example"); await writer.WriteLineAsync("and second line"); } }
Best Regards,
Hart
MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.