Search code examples
c#garbage-collectiondispose

Use of Garbage Collection?


I want to know what action is performed when we call Dispose() method. Is Object frees all resources quickly on Dispose() call or Dispose() marks the Object is ready for garbage collection. And What happened when we set Object reference to NULL. Actually I have Windows form application in .NET 2.0. And I want to call garbage collector after certain time is passed(For Example after 5 mins) to collect all unreferenced Object.


Solution

  • There is nothing magic about the Dispose method, it's just like any other method. Calling the Dispose method doesn't do any cleanup in the background or change the state of the object, it just does what you have put in the method. What is special about it is that it's defined in the IDisposable interface, so it's the standard way of telling an object to clean up it's resources.

    In the Dispose method the object should take care of all unmanaged resources, like database connections and Font objects.

    When you free an object you don't have to bother about any managed resources. A structure like a byte array is completely handled by the garbage collector, and you can just leave it in the object when you let it go. You don't need to set any references to null, when you don't use an object any more, the garbage collector will find the best time to remove it and any objects that it references.

    The garbage collector normally works best when you leave it alone, there is no need to tell it when it should collect unused object. It will figure out by itself when that should be done, and usually it does that better than you, as it has access to a lot of information about the state of the memory and the state of the machine that your code doesn't have.

    You might feel that you should try to keep the memory usage low, but there is no advantage of that in itself. A computer doesn't work better because it has more free memory left. On the contrary, if your code tries to do cleanup, or forces to garbage collector to do anyhting, it is doing the cleanup when it should be busy doing something more important. The garbage collector will clean up unused object if it's needed.