Ensuring Close() gets called.

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

My LogFile class contains a StreamWriter object. How can I ensure that its
Close() method will be called if my program crashes? I don't want to leak
file handles! ;)
 
You won't leak file handles, if the program crashes the OS will free the
handles.

Willy.
 
That's good to know! So I don't have to worry about calling Close() on a log
file?

This is probably a stupid question, but if the program doesn't crash, will
they still be freed? It' sjust that I've heard of leaking file handles, and
I don't know how it would happen if the OS cleans them up. Is that refering
to leaking handles during execution?
 
Willy is correct, however if you want to make sure that your program
exits gracefully you can put your file handling routine into a try
catch finally block, with the file being flushed and closed in the
finally.
 
When the process terminates unexpectedly, the OS has to free the handles, if
the OS can't free the handle it's a bug in the OS.
When your process terminates normally, it's up to you to close the files
(and flush the buffers), if you fail to do this the OS will free the
handles, but there is no guarantee all data is written to the file.
Willy.
 
Back
Top