Share via


Avoiding memory leaks in a windows service

Question

Thursday, September 11, 2014 6:19 PM

How to avoid memory leaks in a windows service? Also need to avoid memory leaks due to usage of FileSystemWatcher class

saikalyan

All replies (2)

Thursday, September 11, 2014 8:34 PM ✅Answered

Are you for some reason instantiating the class in a loop or some other iterative fashion? If so, you may have to check if you need to invoke the FileSystemWatcher.Dispose method to release resources used by the component. This may also be true for other objects you may have in your project. When you instantiate an object, the .NET framework is allocating memory on the managed heap. The memory will stay allocated until it is no longer referenced by any running code. Only then will it be collected by the garbage collector.


Friday, September 12, 2014 8:43 AM ✅Answered | 1 vote

Hi SAI KALYAN,

Firstly, we need to know what can cause a memory leak

  • Static references
  • Event with missing unsubscription
  • Static event with missing unsubscription
  • Dispose method not invoked
  • Incomplete Dispose method

Secondly, how to avoid memory leaks

You can try adding some calls to GC.Collect temporarily to see if that has an effect on memory usage.

As far as i know, change statics to instances the memory consumption decreased noticeably and GC also was able to free much more memory. Don't rely on static helper classes.

By the way, i have found the way to fix Memory leak when you use the FileSystemWatcher

FIX: Memory leak when you use the FileSystemWatcher class in a .NET Framework 4.0-based application

Hope it helpful for you.

Have a nice day!

Kristin

We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click HERE to participate the survey.