Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting if the garbage collector was invoked (.Net)

When using SqlConnection, it's important to always close it when used - either by .Close() or placing the SqlConnection in a "using". Unfurtunately, people, including myself, tend to forgot that and this is where the garbage collectors rescues me for a while until i've forgot to close my connections too many times or the number of people using the application grows.

I'd like to know, if even possible, how to detect if the garbage collector disposed the SqlConnection because it figured that it wasn't in use anymore or if the SqlConnection was closed the correct way.

Another way could be inheriting SqlConnection and putting a timer on it's initializer and check how long it took for the connection to be closed when disposing the class. I don't really like timers but the idea just came up while writing this.

Maybe there's a third and even smarter way to all this... What would you recommend?

like image 230
Jan Sommer Avatar asked Jun 29 '10 18:06

Jan Sommer


People also ask

How do you make sure that the garbage collector is done running when you call?

System. GC. Collect() forces garbage collector to run. This is not recommended but can be used if situations arise.

How is garbage collector invoked in C#?

You can force garbage collection either to all the three generations or to a specific generation using the GC. Collect() method. The GC. Collect() method is overloaded -- you can call it without any parameters or even by passing the generation number you would like to the garbage collector to collect.

Does .NET have a garbage collector?

. NET's garbage collector manages the allocation and release of memory for your application. Each time you create a new object, the common language runtime allocates memory for the object from the managed heap.

Does garbage collector call Dispose C#?

The GC does not call Dispose , it calls your finalizer (which you should make call Dispose(false) ).


1 Answers

Since SqlConnection is sealed, you won't be able to inherit from it. (And I don't think it is a good idea to do so -- If it was possible, you should probably add your code in Dispose(false), because that is what the finalizer calls).

It is better to detect these kind of problems by using a static code analysis tool, which has the power to detect all places in your code where you forget to dispose a connection. There is one built in in Visual Studio, or you can use FxCop.

To help you not to forget disposing the connection, it is a good idea to:

  • Keep all DB connection code in one layer / assembly / module, so it is not scattered through the projects.
  • Have utility methods to perform SQL commands and returning the results; so you don't create SQLConnection more places than you need to.
  • Remember to utilize the C# using construct.
like image 167
driis Avatar answered Sep 22 '22 02:09

driis