简体   繁体   中英

Keep the file open, don't lose data when the app crashes

I need to log info to a file around 1000-2000 times a minute. I also need to save that info in case the app crashes.

Currently here's what I'm doing:

using(StreamWriter sw=new StreamWriter(filename,true))
{
    sw.WriteLine(info);
}

This works, but it's extremely slow.

I'd like to be doing something like this:

static StreamWriter sw=new StreamWriter(file,true);

....

public static void Main(...)
{
    .....
    sw.WriteLine(....);
}

but when I write code like this, I'm afraid that the info I store will get lost when the app crashes.

What can I do to preserve info in the file without having to open and close it all the time?

You can call StreamWriter.Flush() after each write.

public static void Main(...)
{
    .....
    sw.WriteLine(....);
    sw.Flush();
}

But you should use NLog or Log4Net !

I've used this class it implements a queue that is flushed every X message or Y time.

You can improved it moving the using block outside the while in flushLog() and setting a fixed filename

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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