Dispose question

后端 未结 7 1972
北荒
北荒 2021-02-14 02:51

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:10

    I think it's most helpful to describe a managed resource is a class-type object that implements IDisposable and requires cleanup, but can perform such cleanup (typically using Finalize) if it's abandoned without being properly Dispose'd. An unmanaged resource generally refers to an entity which requires cleanup that simply won't happen if it's abandoned without being Dispose'd first. It's important to note that the while the term "managed resource" refers essentially exclusively to class-type objects (which generally override Finalize, but which in some cases may be the targets of WeakReference objects), unmanaged resources may be not only be anything, they may also be anywhere, including on another computer.

    I would suggest that instead of using the term "resource" it's more helpful to think in terms of "responsibilities". Opening a file or socket connection creates a responsibility to close it. Acquiring a lock creates a responsibility to release it. Sending a remote system a "grant me exclusive access to this record" message creates a responsibility to send it an "I'm done with this record" message. If an object's cleanup responsibilites can get carried out even if it's abandoned, it's a "managed resource". Otherwise, it's an "unmanaged resource".

    Merely categorizing things as "managed resources" or "unmanaged resources" is not quite sufficient for deciding how they should be cleaned up. Some unmanaged responsibilities can be conveniently handled by a class-type wrapper which can perform any necessary cleanup in case of improper abandonment. Such wrappers should generally contain a minimal amount of information necessary to perform the cleanup responsibility. Other responsibilities cannot very well be handled automatically. It's often better to ensure Dispose is called than try to handle everything that can happen if it isn't.

提交回复
热议问题