Ensuring Close() gets called.

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! ;)
 
W

Willy Denoyette [MVP]

You won't leak file handles, if the program crashes the OS will free the
handles.

Willy.
 
G

Guest

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?
 
O

orekinbck

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.
 
W

Willy Denoyette [MVP]

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top