C# disposing IDisposable

后端 未结 7 2105
滥情空心
滥情空心 2021-01-14 02:44

Could someone explain what might happen if you don\'t Dispose some IDisposable entity (by using or direct Dispose cal

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-14 03:30

    Not calling .Dispose() could result in a memory leak. Otherwise, not calling Dispose() will simply result in delayed collection by the GC. Overall, the effects will completely depend on what objects are instantiated (see SLaks for a great bullet list). By implementing IDisposable, you are taking responsibility for cleaning up your mess, so to speak.

    What implementation should do is tell the GC (Garbage Collector) that it should suppress collection because you are going to take care of it. That way, when the Dispose() method is called on your IDisposable object, you should have taken care of clean up - i.e., calling Dispose() on objects within that class, clearing collections, etc.

    And, FYI, the using{...} clause can only be used on objects implementing IDisposable because at the closing bracket the Dispose() method is called automatically:

    using (MyDisposableObject dispObj = new MyDisposableObject())
    {
        // use dispObj for some work
    }    // dispObj.Dispose() is automatically called here
    

提交回复
热议问题