I have built an application using Visual Studio .NET and it works fine. After the application is used for more than 2-3 hours it starts to get slow and I don’t know why. I have used GC.Collect(); to get memory leak problems but now I have the new one.
Does anyone know a solution?
I have built an application using Visual Studio .NET and it works fine. After
Share
If you really have a memory leak, just calling
GC.Collect()will get you nowhere. The GarbageCollector can only collect those objects, that are not referenced from others anymore.If you do not cleanup your objects properly, the GC will not collect anything.
When handling with memory consumptions, you should strongly consider the following patterns:
Weak Events (MSDN Documentation here)
If you do not unsubscribe from events, the subscribing objects will never be released into the Garbage Collection.
GC.Collect()will NOT remove those objects and they will clutter your memory.Implement the
IDisposableinterface (MSDN documentation here)(I strongly suggest to read this ducumentation as I have seen lots of wrong implementations.)
You should always free resources that you used. Call
Dispose()on every object that offers it!The same applies to streams. Always call
Close()on every object that offers this.To make points 2. and 3. easier you can use the
usingblocks. (MSDN documentation here)As soon as these code blocks go out of scope they automatically call the appropriate
Dispose()orClose()methods on the given object. This is the same, but more convinient, as using atry... finallycombination.