刷新StreamWriter后是否需要刷新流?
@H_404_5@解决方法
public static async Task WriteStringAsync(this Stream stream,string messageString) { var encoding = new UTF8Encoding(false); //no BOM using (var streamWriter = new StreamWriter(stream,encoding)) { await streamWriter.WriteAsync(messageString); await streamWriter.FlushAsync(); } await stream.FlushAsync(); //is this necessary? }
根据MSDN文档,这可以被原谅为“只是确保”……
StreamWriter.Flush():
Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream.
Stream.Flush():
When overridden in a derived class,clears all buffers for this stream and causes any buffered data to be written to the underlying device.
…但是,仔细查看TypeDescriptor中的代码会显示StreamWriter.Flush()(我假设它的异步对应FlushAsync)是一个调用主函数的重载,传递两个布尔参数,指示StreamWriter刷新Stream和Unicode编码器也是如此.因此,一次调用StreamWriter.FlushAsync(),再加上await关键字以确保完全发生异步操作,应该没问题.