我怎么能写从C#服务的日志文件,这样它就会被刷新到磁盘及时?
How can I write a logfile from a C# service so that it gets flushed to disk in a timely fashion?
下面是我已经试过。在记录code,我打开一个文件是这样的:
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);
和写信给它这样的:
writer.WriteLine(msg);
writer.Flush();
file.Flush();
但是日志没有刷新到磁盘及时。所以,我想补充,这是否一个5秒钟的定时器:
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?
每这个答案,.NET 4.0下它的不够的,只是叫
Per this answer, under .NET 4.0 it's enough to just call
file.Flush(true)
瞎搞与P / Invoke调用不再需要。
Messing around with the p/Invoke call is no longer required.