Managing unmanaged resources

The garbage collection provided by the .NET Framework is good enough when we are dealing with managed objects. However, there are several instances in which we need to use unmanaged resources in our code. Some of these instances include the following:

  • When we need to access OS memory using pointers
  • When we are doing I/O operations related to file objects

In each of these circumstances, the garbage collector does not explicitly free up the memory. We need to explicitly manage the release of such resources. If we do not release such resources, then we may end up with problems related to memory leaks in the application, locks on OS files, leaks on connection threads to resources such as databases, and more. 

To avoid these situations, C# provides finalization. Finalization allows us to cleanup unmanaged code in a class before the garbage collector is invoked.

Please note that when using finalization, we cannot control when the code specified in finalization will be called. It's up to the garbage collector to determine when the object is no longer required. However, what we are sure of is that the finalization code will be called before the object gets cleaned up by the garbage collector. 

To declare a finalizer in a class, we use the ~ syntax. The following is the code implementation we use to declare a finalizer for a particular class in C#:

public class SampleFinalizerClass
{
~SampleFinalizerClass()
{

}
}

In the preceding code example, we have declared a SampleFinalizerClass syntax. In order to clean up unmanaged resources in the class, we have declared a finalizer. The name of the finalizer is the same as that of the class but is appended with a ~.

In Finalizer, we can do things such as destroying pointer objects, releasing connections on files, releasing connection threads to databases, and more.

Now, although using the Finalizer keyword does clean up  unmanaged code before the object is destroyed by the garbage collector, it does introduce some extra overhead for the garbage collector. Let's examine the following example in order to understand the reason behind this overhead.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.192.59