I want to know about unmanaged resources. Can anyone please give me a basic idea?
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++.
Managed resources are those that are pure . NET code and managed by the runtime and are under its direct control. Unmanaged resources are those that are not. File handles, pinned memory, COM objects, database connections etc.
UnManaged objects are created outside the control of . NET libraries and are not managed by CLR, example of such unmanaged code is COM objects, file streams, connection objects, Interop objects. (Basically, third party libraries that are referred in .
So, the garbage collector is nothing but a background thread that runs continuously. Checks for unused managed objects clean those objects and reclaims the memory. Now, it is important to note that the garbage collector cleans and reclaims unused managed objects only. It does not clean unmanaged objects.
Managed resources basically means "managed memory" that is managed by the garbage collector. When you no longer have any references to a managed object (which uses managed memory), the garbage collector will (eventually) release that memory for you.
Unmanaged resources are then everything that the garbage collector does not know about. For example:
Normally you want to release those unmanaged resources before you lose all the references you have to the object managing them. You do this by calling Dispose
on that object, or (in C#) using the using
statement which will handle calling Dispose
for you.
If you neglect to Dispose
of your unmanaged resources correctly, the garbage collector will eventually handle it for you when the object containing that resource is garbage collected (this is "finalization"). But because the garbage collector doesn't know about the unmanaged resources, it can't tell how badly it needs to release them - so it's possible for your program to perform poorly or run out of resources entirely.
If you implement a class yourself that handles unmanaged resources, it is up to you to implement Dispose
and Finalize
correctly.
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