Archived

This topic is now archived and is closed to further replies.

Where to close file handle? (c#)

This topic is 5152 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

In my log class I have a StreamWriter object which I initialize in the log''s constructor. Now when the log class is destroyed, the file handle should be closed (Close method). Obvious place seems to be the destructor? No. Whatever I do with the file handle in the destructor has no effect. Usually this throws an exception. For example if I want to write "Log closed", exception is thrown (It said that the StreamWriter was already closed). Now where should the handle be closed?

Share this post


Link to post
Share on other sites
I'm actually using the Dispose thingie at the moment. But the idea is that user shouldn't have to do anything for the logger to close the file correctly. Now user has to call the Dispose manually, and if I let the log's Finalize method (destructor) call it, it is already closed!

edit: The problem is that even though the StreamWriter is already closed in the destructor when I try to close it, nothing is flushed to the disk.

[edited by - Miksan on November 10, 2003 3:08:21 PM]

Share this post


Link to post
Share on other sites
The problem is that you have absolutely NO control over when the destructor runs - it may not even run at all. IIRC, when an object that has a destructor gets garbage collected, the object does not get cleaned up right away - it merely gets put in another queue and the destructor doesn''t get run until the next collection. Additionally, when the CLR is shutting down, it allocates a specific time period for all remaining destructors to be executed. When this interval elapses, it shuts down regardless of whether there are any remaining destructors in the finalizer queue. In addition, you have no control over the sequence in which destructors are run.

The behavior you are seeing(StreamWriter already being closed) is probably due to this - when your Log destructor is being run, the destructor for the StreamWriter has already been run and the stream is closed.

quote:

The problem is that even though the StreamWriter is already closed in the destructor when I try to close it, nothing is flushed to the disk.


This sounds a bit weird - I''d think that the StreamWriter would flush the stream when closing it. Anyway, maybe you should try setting the AutoFlush property? I''d say that would make sense for a logging class anyway, since you never know how your application will be terminated, and it''s usually in the situations when it''s not terminated properly that the log data is of most interest.

Share this post


Link to post
Share on other sites