Dispose question

后端 未结 7 1836
無奈伤痛
無奈伤痛 2021-02-14 02:17

I have a number of classes which have private member variables that implement IDisposable (timers, brushes, etc). Do I need to do anything to ensure these variables are cleaned

相关标签:
7条回答
  • 2021-02-14 03:24

    Three simple rules.

    A managed resource is anything implementing IDisposable. An unmanaged resource is something like a HANDLE that you got via p/Invoke. A class like SafeHandle (or one derived from SafeHandle) owns an unmanaged resource, but it is considered a managed resource itself. So any class that owns unmanaged resource is itself a managed resource.

    Since you have a class owning managed resources, follow Rule 2: implement IDisposable (but not a finalizer).

    IDisposable allows for earlier cleanup. If you don't call it, the resources will be cleaned up anyway (they won't hang around until process exit); they'll just be cleaned up later, and you don't have a choice about when they get cleaned up.

    0 讨论(0)
提交回复
热议问题