Search code examples
c#wpfmemory-leaksprismidisposable

Memory is not released after dispose method is calling in wpf prism


I have navigating from one window to another modal window. There are 10 observable collection. After closing the window, i have set null to the all observable collection. But in task manager the memory is not reduced. When I open the modal window 25 mb is increased but when i close the window only 1mb or 2mb only reduced after disposing all observable collection.

private bool disposedValue = false;
protected virtual void Dispose(bool disposing)
{
   if (!disposedValue)
   {
       if (disposing)
       {
           Collection1 = null;
           Collection2 = null;
           Collection3 = null;
           Collection4 = null;
           Collection5 = null;
       }
       disposedValue = true;
   }
}

Please suggestion me i have did anything wrong. Please share your valuable suggestion. I have also checked the memory consumption in visual studio Diagnostic Tools.


Solution

  • Not sure about the negative side , but work for sure

    public class MemoryManagement
        {
            /// <summary>
            /// Clear un wanted memory
            /// </summary>
            public static void FlushMemory()
            {
                try
                {
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    if (Environment.OSVersion.Platform == PlatformID.Win32NT)
                    {
                        SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
                    }
                }
                catch (Exception e)
                {
                }
            }
    
            /// <summary>
            /// set process working size
            /// </summary>
            /// <param name="process">Gets process</param>
            /// <param name="minimumWorkingSetSize">Gets minimum working size</param>
            /// <param name="maximumWorkingSetSize">Gets maximum working size</param>
            /// <returns>Returns value</returns>
            [DllImportAttribute("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize", ExactSpelling = true, CharSet =
              CharSet.Ansi, SetLastError = true)]
            private static extern int SetProcessWorkingSetSize(IntPtr process, int minimumWorkingSetSize, int maximumWorkingSetSize);
        }
    

    Call MemoryManagement.FlushMemory() in the Dispose