views:

78

answers:

3

I have created a windows service which is continuously polling a database. For this purpose i have a timer in place. Ever time i am querying a database table i open a connection and close it immediately after my work is done. Right now i am doing this every 20 seconds for testing purpose, but later this time might increase to 5 - 10 minutes.

What happens is every time the database table is polled there is an increase of 10-12 KB in the size of the memory of the service running. This i can see in the task manager. Is there any way to control this.

A: 

The memory of a .NET application is managed by the CLR and it is not recommended to interfere with it. I would instead advice you to profile your service and try to understand why it is leaking memory.

What do you do with the results of the query? Do you store them in memory (some static objects)?

Make sure you use using blocks around disposable resources such as SqlConnection and SqlCommand.

The garbage collector should take care of freeing resources.

Darin Dimitrov
+1  A: 

The garbage collector should eventually kick in and free up some memory. It isn't based on time, but rather memory pressure. So you should be able to simulate longer durations by just increasing the frequency of your polling. If the GC doesn't reclaim any memory then you've got a leak somewhere. Also don't forget that database connections typically use connection pooling which means even though you're done with the connection, a pool of active connections is still waiting around.

But it's very normal not to see memory reclaimed instantly. Resist the urge to use GC.Collect unless its just for debugging. It could impact the efficiency of the garbage collector.

Josh Einstein
A: 

Check if you have a memory leak. I use Windbg for this, as explained in CLR Memory Leak:

  • !dumpheap -stat to see the statistics of each type
  • !dumpheap -type <LeakedTypeName> to see the instances of the supposed leaked type
  • !gcroot <AddressOfObject> to track the reference that pins the allocation (ie. the cause of the leak).
Remus Rusanu