开发者

how to catch program shutdown to release resources?

In my program i'm using

logWriter = File.CreateText(logFileName);

to store logs.

Should I call logWriter.Close() 开发者_如何学Pythonand where? Should it be finalizer or something?


The normal approach is to wrap File.CreateText in a using statement

using (var logWriter = File.CreateText(logFileName))
{
    //do stuff with logWriter 
}

However, this is inconvenient if you want logWriter to live for the duration of your app since you most likely won't want the using statement wrapping around your app's Main method.

In which case you must make sure that you call Dispose on logWriter before the app terminates which is exactly what using does for you behind the scenes.


Yes you should close your file when you're done with it. You can create a log class ( or use an existing one like log4net ) and implement IDisposable and inside the Dispose-method you release the resources.

You can wrap it with a using-block, but I would rather have it in a seperate class. This way in the future you can handle more advance logging, for instance, what happens when your application runs on multiple threads and you try to write to the file at the same time?

log4net can be configured to use a text-file or a database and it's easy to change if the applications grows.


If you have a log file which you wish to keep open, then the OS will release the file as part of shutting the process down when the application exits. You do not actually have to manage this explicitly.

One issue with letting the OS clean up your file handle, is that your file writer will use buffering and it may need flushing before it will write out the remains of its buffer. If you do not call close\dispose on it you may lose information. One way of forcing a flush is to hook the AppDomain unload event which will get called when your .Net process shuts down, e.g.:

AppDomain.CurrentDomain.DomainUnload += delegate { logWriter.Dispose(); };

There is a time limit on what can occur in a domain unload event handler, but writing the remains of a file writer buffer out is well within this. I am assuming you have a default setup i.e. one default AppDomain, otherwise things get tricky all round including logging.

If you are keeping your file open, consider opening it with access rights that will allow other processes to have read access. This will enable a program such as a file tailer or text editor to be used to read the file whilst your program is running.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜