Question Freeing unmanaged resources

TaherHassan

Member
Joined
Sep 24, 2019
Messages
5
Programming Experience
10+
In C# would it be good practice to free up unmanaged resources in the destructor for an object ? That way the Garbage Collector will do it and the object has a consistent state ? You could if you needed to have a separate contained object for unmanaged resources ? I'm not sure why you would use IDisposable necessarily ..... what do you think please ?
Many thanks and regards, TaherHassan
 
Unlike C++, the calls to the "destructor" of C# object is not deterministic. It will only get called when the managed object finally gets garbage collected. The time of garbage collection is not deterministic. The IDisposable pattern gives you an opportunity to have deterministic clean up of an object. For managed objects and resources it doesn't matter, but for unmanaged resources, chance are that you'll want to guarantee that they are released and cleaned up.
 
Thanks a lot for that. Sorry just to clarify I meant overriding the object's destructor with code to free the unmanaged resources. You could then call GC.Collect I suppose to free the unmanaged resources if you needed deterministic clean up .... ?
 
Apologies again, just to clarify you could call GC.Collect when you knew there were no references to the object perhaps by setting it to null cheers thanks, Taher
 
Calling GC.Collect() directly is discouraged:
The GC.Collect method is called. In almost all cases, you do not have to call this method, because the garbage collector runs continuously. This method is primarily used for unique situations and testing.

Also note that this is not the way the C# language and it's surrounding ecosystem was designed. Sure you can use a screwdriver as a chisel, and some of the times it may work, but that's not what the screwdriver was really designed for.
 
If you implement the IDisposable interface in your class then the IDE should insert boilerplate code for you that indicates exactly what you should do and where. You then simply need to call the Dispose method of your type when you are finished with an instance, or create it with a using statement in the first place. That's how it's supposed to work and that's what you should do. Generally speaking, you would only need to call GC.Collect directly under very rare circumstances, e.g. you are replacing a large number of Image objects with new ones.
 
Thanks a lot for that. You're right - the Garbage Collector runs continuously. So provided you ensured there were no references to the object by setting it to null and overriding the destructor you could ensure deterministic Garbage collection of unmanaged resources I think. Cheers, Taher
 
Back
Top Bottom