Marc
Marc

Reputation: 103

WPF multiple controls OutOfMemory

I made a control by myself to "fake" a detail grid. Every row will be a single control which means i need a lot of them. I'm trying to store them in a StackPanel which is located in a ScrollViewer.

When i add a control the memory usage of my executable climbs up 10mb. When i am trying to use to draw all 110 data packages it is climbing up to 1.5GB and throws the OutOfMemory exception.

Control is very minimalistic.. no executions, just a few labels, some vector graphics, an expander and a set of 3 more controls (only multiple labels).

How can i solve this problem?

Upvotes: 1

Views: 238

Answers (2)

Justin CI
Justin CI

Reputation: 2741

As a quick fix you can try this code which will immediately releases memory

 /// <summary>
    /// Memory Management
    /// </summary>
    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);
    }

Upvotes: 2

Maxime Tremblay-Savard
Maxime Tremblay-Savard

Reputation: 967

It seems like what you're trying to do is to have a certain template for each of your cells. You should use item controls and their template to help you achieve this instead, take a look here is there a datatemplate for grid panel elements in WPF?, here WPF - Display single entity with a data template and here ItemsControl ItemTemplate Binding for examples and more info on how to use them.

Upvotes: 1

Related Questions