Can I expect that a stream is closed by the garbage Collector?
i have a class like a stream with a "Close" function. The instance of this class is stored in a Field/Attribute. Sometimes I have to replace this instance with a fresh one. Unfortunally I can't find out if someone still uses the old instance of the Object.(Many Many functions use this field with Multithreading). So I can just overwrite the field without closing the class. Can I expect that the GC removes th开发者_开发问答e not closed object oder can I close it in the dispose function?
Thanks.
Your class should be implementing IDisposable
and any user of it should be instantiating it in a using
statement.
This will ensure correct closing/disposal.
The GC will not close/dispose of classes that are still referenced, so it really depends on the code you have written and how the class is being used.
You not just can close it with the dispose method, but you have to close it, as a stream most like contains unmanaged resources, which the garbage collector can't take care of. Always Dispose
classes implementing IDisposable
if you are done using them.
If you use classes implementing IDisposable
in a class, your class should implement the interface as well.
FileStream
et al. do have a Finalize() method, which just calls Dispose()
. While it's true that this will guarantee that the handles get closed eventually, it's not deterministic. If you can manually close the streams yourself, that is the highly preferred method. The Finalize()
method is only there in case somehow the stream doesn't get closed manually (usually due to a bug in your logic).
As it happens, even the Finalize()
method isn't 100% guaranteed to be called. However, once your program exits, all handles will be closed by the OS.
If your class has a finalizer, then yes. But, given your description, that's not the point.
Most likely, you want the class to implement IDisposable
, so you can release unmanaged resources (or owned disposable instances) at the earliest time possible.
But there seem to be bigger design issues. Given that you have control over the field, you should know when it's safe to create a new instance and/or when to dispose of it. Apparently you have some shared instance across threads, without something that has clear ownership of that instance. Without code, and more detailed description, it's possible I'm wrong, but it sounds like an accident waiting to happen.
精彩评论