Proper use of the IDisposable interface

后端 未结 19 3263
情深已故
情深已故 2020-11-21 04:05

I know from reading the Microsoft documentation that the \"primary\" use of the IDisposable interface is to clean up unmanaged resources.

To me, \"unman

19条回答
  •  甜味超标
    2020-11-21 04:55

    Yep, that code is completely redundant and unnecessary and it doesn't make the garbage collector do anything it wouldn't otherwise do (once an instance of MyCollection goes out of scope, that is.) Especially the .Clear() calls.

    Answer to your edit: Sort of. If I do this:

    public void WasteMemory()
    {
        var instance = new MyCollection(); // this one has no Dispose() method
        instance.FillItWithAMillionStrings();
    }
    
    // 1 million strings are in memory, but marked for reclamation by the GC
    

    It's functionally identical to this for purposes of memory management:

    public void WasteMemory()
    {
        var instance = new MyCollection(); // this one has your Dispose()
        instance.FillItWithAMillionStrings();
        instance.Dispose();
    }
    
    // 1 million strings are in memory, but marked for reclamation by the GC
    

    If you really really really need to free the memory this very instant, call GC.Collect(). There's no reason to do this here, though. The memory will be freed when it's needed.

提交回复
热议问题