Why code analyzers recommend to dispose IDisposable fields?

This question already has an answer here:

  • Why is it always necessary to implement IDisposable on an object that has an IDisposable member? 7 answers

  • There are 2 reason to implement IDispose:
    1. Disposal of unmanaged resources - this is about WHAT to clean up (the unmanaged resources)
    2. To be able to control when managed resources are freed - this is about WHEN things get cleaned up .
    The IDisposable documention focuses very heavily on 1. but in in reality most implmentations are about 2.
    That is the case in your example - the resources you have are managed (by the managed Bitmap class that wraps the unmanaged bitmap handle). You would dispose it in your dispose to enable users of your class to control when the bitmap was freed (NOT if it gets freed - it will be, eventually, when the GC feels like it).


    Maybe it will. But when? This class cannot reliably be used. If I create 10.000 sequentially, 10.000 undisposed Bitmaps will be in memory, waiting for the lazy garbage collector to call the finalizer to (hopefully) call Dispose . Maybe today. Maybe tomorrow. But as a developer, I cannot control this. If you implement IDisposable correctly, I can simply have a using block around each of them and I will never use more resources than a single Bitmap will take.

    链接地址: http://www.djcxy.com/p/54324.html

    上一篇: Asp.Net Web API和WCF Service有什么区别?

    下一篇: 为什么代码分析器建议处理IDisposable字段?