Is Close() same as Using statement

喜夏-厌秋 提交于 2020-04-21 02:30:22

问题


Is Close() same as Dispose() or using statement. Is it necessary to call using statement even if Close is called?.

I know before disposing of an object, close should be called, so we close the resource and may it available to Dispose.

https://msdn.microsoft.com/en-us/library/aa355056(v=vs.110).aspx

says Close is same as Dispose.


回答1:


Close() has no relation to IDisposable interface, see: https://msdn.microsoft.com/en-us/library/system.idisposable(v=vs.110).aspx

using only applies to IDisposable inherited objects, see: https://msdn.microsoft.com/en-us/library/yh598w02.aspx

Close() and Dispose() may not considered to be related in any way.

When the IDisposable interface is correctly implemented, you may assume all clean-up necessary will be carried out. This implies an internal call to a Close() method would be carried out. This means that an explicit call to Close() should not be necessary.

The other way round; when a object is of type IDisposable and exposes a Close() method, a call to Close() will not be sufficient to properly dispose/clean-up the object. Dispose() must still be called, you can do this directly, or through the using statement.

You can also let the garbage-collector handle the Dispose() call for you (if its correctly implemented, see: Proper use of the IDisposable interface) But this is considered bad-practice, since you need to rely on a proper implementation and have no direct control over the GC timing.

Please note, a reason to implement a Close() function, is usually to give a developer a way to reuse the object. After calling Dispose() the object is considered to be marked for finalization and may not be used any more.




回答2:


The using pattern is useful because it includes a try ... finally ... that will protect against exceptions...

If you do:

FileStream fs = null;

try
{
    fs = File.OpenRead("MyFile.txt");
}  
finally
{
    if (fs != null) 
    {
        fs.Close();
    }
}

then in this case it would be nearly equivalent (because the Stream.Close() calls the Dispose(true))

BUT it is still "wrong"... You use using for IDisposable classes unless you have a very very good reason (there are some reasons for not doing it... Sometimes the lifetime of an object is very very difficult to track. In that case it is normally ok to no Dispose() it.).

The concept of a pattern is that it should become part of you... If you try to skirt from a pattern, then before or later you'll forget about it... And for what? For writing MORE lines that are MORE error-prone?




回答3:


Not necessarily. I can write a class that has a Close and a Dispose method that aren't related.

class Foo : IDisposable
{
    public void Close() { DoBar(); }
    public void Dispose() { DoBaz(); }
}


来源:https://stackoverflow.com/questions/42719398/is-close-same-as-using-statement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!