Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dispose pattern: How do I know what's managed and what's unmanaged?

Reading about the Dispose pattern, I see the documentation repeatedly refer to "cleaning up managed and unmanaged code". And in the canonical implementation of the Dispose method, I see specific flows (depending on whether disposing is true or false) dedicated to the cleanup of managed objects versus unmanaged objects.

But am I, the lowly newbie, to know which types are managed and which are unmanaged?

like image 886
Jeff Stewart Avatar asked Jul 10 '09 21:07

Jeff Stewart


People also ask

What are unmanaged resources?

Unmanaged resources are those that run outside the . NET runtime (CLR)(aka non-. NET code.) For example, a call to a DLL in the Win32 API, or a call to a . dll written in C++.

How do you use the Dispose method?

The Dispose method performs all object cleanup, so the garbage collector no longer needs to call the objects' Object. Finalize override. Therefore, the call to the SuppressFinalize method prevents the garbage collector from running the finalizer. If the type has no finalizer, the call to GC.

Which method is overridden to clean up unmanaged resources?

A: Automatic way by Finalizer and GC Object declares a virtual method Finalize that is called by the GC before the object's memory is reclaimed by the GC and can be overridden to release unmanaged resources. Types that override the finalizer are referred to as finalizable types.


2 Answers

Unmanaged means native Win32 objects, chiefly handles; and references to raw COM objects. These are resources that are not under the control of (or managed by) the .NET CLR.

like image 91
John Saunders Avatar answered Oct 11 '22 12:10

John Saunders


The short version is: anything that also implements IDisposable needs to be called in your Dispose method. FxCop will also tell you if you're missing something (or not using IDisposable at all when you should be).

like image 24
Matthew Scharley Avatar answered Oct 11 '22 13:10

Matthew Scharley