c# – 需要双重冲洗吗?

前端之家收集整理的这篇文章主要介绍了c# – 需要双重冲洗吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
刷新StreamWriter后是否需要刷新流?
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?
}
@H_404_5@解决方法
根据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关键字以确保完全发生异步操作,应该没问题.

猜你在找的C#相关文章