Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

doubts regarding Memory management in .net

I'm learning about Memory management in C# from the book "Professional C#"

The presence of the garbage collector means that you will usually not worry about objects that you no longer need; you will simply allow all references to those objects to go out of scope and allow the garbage collector to free memory as required. However, the garbage collector does not know how to free unmanaged resources (such as file handles, network connections, and database connections). When managed classes encapsulate direct or indirect references to unmanaged resources, you need to make special provision to ensure that the unmanaged resources are released when an instance of the class is garbage collected.

When defining a class, you can use two mechanisms to automate the freeing of unmanaged resources.

  1. Declaring a destructor (or finalizer) as a member of your class.
  2. Implementing the System.IDisposable interface in your class.

I didn't understand few things:

  1. "unmanaged resources (such as file handles, network connections, and database connections)". Whats the big deal about them? How come they are unmanaged? (or) Why can't GC managed these resources?

  2. What code would we place in finalizer or Dispose() method of the a class and what exactly that code would look like? Some examples using these resources, would be of lot of help.

like image 927
claws Avatar asked Nov 06 '09 15:11

claws


1 Answers

Some classes on the .NET framework are just wrappers of Windows APIs or third party assemblies. These APIs are not managed code (they can be written in C++ or they are old COM assemblies) and the garbage collector does not know when they are no longer required by the application.

For example, when you open a file of disk, it will remain open until you tell it to close the file. If you destroy the pointer to the file (i.e. leaving the scope) without closing the file, this file will remain open and locked.

The Dispose method implemented on the Framework for these classes calls the inner Close method required to finalize the instance in a clean way. So all the classes that wrap unmanaged code should implement the Disposable interface to assure that a closing method it's implemented.

Then when you instance that class it is a good practice to do it with the using statement because then when you leave the scope the Dispose method is called automatically.

like image 111
David Espart Avatar answered Sep 22 '22 23:09

David Espart