Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Release native resources

I am relatively new to .net. As I was trying to grasp the concept of Garbage Collection(from "CLR via C#"), I came to know how strong is the Garbage collection approach. But then as I read I understood that native resources allocated should be released. The methods are:
i) Making our type derive from CriticalFinalizerObject type
ii) Using Dispose Pattern using the using statement

Questions in my mind:
1) I am bit confused when to use what?
2)Also isn't it more heavy for the CLR to shift the non-garbage objects down to compact the heap?
3) Any other article suggestion for reading and understanding the concept more thoroughly.

Please correct me if I am mistaken in any of my above statements
Regards,
Justin Samuel.

like image 603
Justin Samuel Avatar asked Jun 17 '26 09:06

Justin Samuel


2 Answers

  1. You want to derive from CriticalFinalizerObject in the case where the usage of your type should be treated as a constrained execution region or CER for short. A CER is an area of code that must complete without exception and in my experience they are not used that often (but that doesn't mean they aren't useful).

    Implementing the IDisposable interface is a bit different - this interface offers a deterministic way of cleaning up after your type once the consumer of it no longer needs it. This is often used to clean up unmanaged resources (like database connections and file handles).

  2. Yes, the garbage collector will have to move many objects in memory during its compact phase but this isn't really something that can be helped. Objects will be moved when virtual memory becomes fragmented and this is something that is outside of your control since the garbage collector is completely responsible for the managed heap. The best practice in this case is to build your types to work as best as possible and only worry about the garbage collector when instrumentation proves that it has become an issue.

  3. I will see if I can find some more helpful articles but CLR via C# is pretty much the best information you will be able to find on this topic.

like image 68
Andrew Hare Avatar answered Jun 18 '26 22:06

Andrew Hare


I recommend this article on Dispose, Finalization, and Resource Management.

What you use depends a lot on what type of programming you do. Based on personal experiences, I've found:

  • Most of the time the only resource management I have to do is wrap any object that implements IDisposable in a using block.
  • Occasionally I have to implement the Basic Dispose Pattern (no finalizer) when my class owns an object that implements IDisposable.
  • I have never had to derive from CriticalFinalizerObject.

Your mileage may vary.

like image 35
TrueWill Avatar answered Jun 18 '26 23:06

TrueWill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!