Flushing log to disk, exception in VerifyOSHandlePosition

允我心安 提交于 2019-12-04 05:30:40

问题


How can I write a logfile from a C# service so that it gets flushed to disk in a timely fashion?

Here's what I've tried. In logging code, I opened a file like this:

var file = return File.Open(name, FileMode.Append, 
                            FileAccess.Write, FileShare.Read);
var writer = new StreamWriter(file);

and wrote to it like this:

writer.WriteLine(msg);
writer.Flush();
file.Flush();

However the log was not flushed to disk in a timely fashion. So I tried adding a 5-second timer that does this:

[DllImport("kernel32.dll")]
static extern bool FlushFileBuffers(IntPtr hFile);

file.Flush();
var hdl = file.SafeFileHandle;
FlushFileBuffers(hdl.DangerousGetHandle());

This appears to work, but at infrequent intervals I get the following exception:

System.IO.IOException: The OS handle's position is not what FileStream expected. Do not use a handle simultaneously in one FileStream and in Win32 code or another FileStream. This may cause data loss.

at System.IO.FileStream.VerifyOSHandlePosition()

Is there a better way to force the flush?


回答1:


Per this answer, under .NET 4.0 it's enough to just call

file.Flush(true)

Messing around with the p/Invoke call is no longer required.



来源:https://stackoverflow.com/questions/9195807/flushing-log-to-disk-exception-in-verifyoshandleposition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!