简体   繁体   English

使用TextWriter时文本文件无法立即更新

[英]Text file not updating right away when using TextWriter

I am using TextWriter to write serial data coming every 100ms on a text file. 我正在使用TextWriter将每100ms的串行数据写入一个文本文件。 But the text file is not updated right away. 但是文本文件不会立即更新。 Sometimes it takes few seconds and sometimes a minute for the written text to be shown on the .txt file. 有时,在.txt文件中显示书面文本需要几秒钟,有时还需要一分钟。 How can i fix that? 我该如何解决?

   TextWriter tw;

    tw = new StreamWriter(new FileStream(path + "\\" + currentSubdirName + "\\" + currentFileName, FileMode.CreateNew));
    tw.Write(text);

The data is only written when the relevant buffers are filled. 仅当相关缓冲区已满时才写入数据。 You can force a flush using tw.Flush() , which will push the (partial) data from the TextWriter to the FileStream . 您可以使用tw.Flush()强制刷新,这会将(部分)数据从TextWriter推送到FileStream

Note that this may have a significant impact on performance, though. 请注意,这可能会对性能产生重大影响。 Caching and buffering are quite important, since disks are just so much slower than RAM (and RAM is much slower than the CPU). 缓存和缓冲非常重要,因为磁盘要比RAM慢得多(RAM比CPU要慢得多)。 Make sure the cost is worth the benefits, and consider only flushing once in a while anyway. 确保成本物有所值,无论如何都应考虑仅偶尔冲洗一次。

You need to call flush for any buffered data to be written to the file immediately 您需要调用flush以便将所有缓冲数据立即写入文件

 TextWriter tw = new StreamWriter(new FileStream(path + "\\" + currentSubdirName + "\\" + currentFileName, FileMode.CreateNew));
 tw.Write(text);
 tw.Flush();
 tw.Dispose();

or alternatively you can using TextWriter in a using statement which will flush all the buffered data on TextWriter.Dispose, This way you need not to handle Writer.Dispose 或者,您也可以在using语句中使用TextWriter,该语句将刷新TextWriter.Dispose上所有缓冲的数据,这样就无需处理Writer.Dispose

using (TextWriter tw = new StreamWriter(new FileStream(path + "\\" + currentSubdirName + "\\" + currentFileName, FileMode.CreateNew));)
{
    tw.Write("test");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM