Did you like how we did? Rate your experience!

4.5

satisfied

46 votes

What are the ways to manage memory in C# WPF applications?

First off C# is a managed language, so you dont have to manage memory in the same way that you would in a C or C++ application. The garbage collector will automatically clean up objects that are no longer referenced. This doesnt mean you cant have memory leaks - if an object is still accessible to your code then the GC wont collect it. In my experience these leaks typically come from a few different places: You have an object that maintains a reference to something that it no longer needs e.g. when you create a new object you add it to a collection and then forget about removing from the collection when you are done. Static references - a static property or field will hold on to an object and its entire object tree for the lifetime of the application (unless you explicitly set it to null or another value) Event Handlers - when you attach to an event, the event holds a reference to the handler - if you dont detach from that event then the event listener (and anything it references) will stay alive until the object containing the event is no longer referenced. 3rd Party Libraries Given your app is WPF, Id look into whether your event handlers are being detached properly first. You can use tools like dotMemory (JetBrains) or ANTS Memory Profiler (Red Gate) to help diagnose memory issues. If after profiling you realize that your application really needs all the data its holding in memory you would have to look at other strategies. You could restructure how you use/process your data so as to not require it all in memory at once. If this is the case a lot would depend on what your application is doing. You could also switch to 64 bit, which will increase the amount of memory available to your application. This just ignores the problem however and could have performance implications for your app (and the rest of your PC) - especially if you have less physical RAM than your app is using. If you do have a memory leak the amount of memory your application uses could grow to be a significant problem for your whole system.

100%
Loading, please wait...