I am not a comp science guy. Managed resources are allocated on the heap. But I would like to know where unmanaged resources are allocated. If unmanaged resources are also allocated on the heap, is it the same heap used by managed resources or a different one?
Thanks in advance.
Harsha
The most common types of unmanaged resources are objects that wrap operating system resources, such as files, windows, network connections, or database connections.
Now, it is important to note that the garbage collector cleans and reclaims unused managed objects only. It does not clean unmanaged objects.
Unmanaged objects are wrapped around operating system resources like file streams, database connections, network related instances, handles to different classes, registries, pointers, etc. Unmanaged resources can be cleaned-up using 'Dispose' method and 'using' statement.
IDisposable interface provides a mechanism for releasing unmanaged resources, so it should be used only if you use them like: file streams, database connections, sockets, memory allocation, etc. This is basically Explicit resources cleanup.
Essentially the heap is the same speaking from the operating system view: the memory space assigned to the OS process.
The difference is that when the CLR (.net VM) loads inside a Windows process it takes a piece of this heap and turns it into a managed heap. This memory space becomes the place where all managed resources are allocated and known to the garbage collector.
For instance, you can run into a Out of Memory error if you allocate a big chunk of unmanaged memory and run out of space for your managed heap. Or the other way around.
Jeffrey Richter is the guy that better explains this stuff. I highly recommend reading his explanation:
You can use the services of the System.InteropServices namespace, the Marshal class specifically, to copy data between the unmanaged part of the heap and the managed.
To operate with unmannaged heap use Marshal class described at MSDN
http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal(v=vs.71).aspx
Unmanaged heap doesn't controlled by GC, so all responsibility of memory usage lies on you. Essentially to release memory that allocated for unmanaged resources use IDisposable interface and release all allocated resources by yourself. All unmanaged resources like SQL connections and different IO operations are using this approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With