Dispose question

后端 未结 7 1856
無奈伤痛
無奈伤痛 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:09

    Yes - if your class "contains" an IDisposable, that class should almost certainly implement IDisposable too.

    "Managed" resources are basically memory. "Unmanaged" resources can be file handles, network connections, handles to graphics objects etc. In most cases types which have direct access to native handles have finalizers, so the resource will be released at some point, but it's still better to release it explicitly - in some cases (such as with HttpWebResponse) there can be a limited number of such resources available (connections in a connection pool to a single host in this case) and you can end up timing out waiting for a "dead" resource to be freed.

    Where possible, it's nicer not to have such class members in the first place - have them as method parameters of local variables etc, so you can use them and then close them without tying the lifetime of the resource to the lifetime of your object. However, in some cases that's not appropriate - in which case you should implement IDisposable.

提交回复
热议问题