Program takes too much memory

梦想的初衷 提交于 2019-11-28 11:20:45

问题


I'm using WPF to develop a simulator of Conway's Game of Life.

From some reason, sometimes the program takes up to 400,000K memory (When I draw a lot of cells really fast).

How can I reduce the memory usage and/or reduce the lags caused by it.

Edit 1: Main Window Code: http://pastebin.com/mz0z7tBu

Grid class: http://pastebin.com/ZHX1WBuK

cell struct:

struct Cell
{
    public int Neighbors {get; set;}
    public bool Alive { get; set; }
}

Edit 2: I'll try to explain Program Structure: Cell is a structure that contains AutoProperty neighbors ofType int, and AutoProperty IsAlive ofType bool.

CellGrid is a Class that wraps a 2D array of Cells. Every iteration, each Cell's Neighbors property is updated to contain the number of Neighbors alive, and then each Cell's IsALive is set to true or false, depends on number of neighbors and previous IsAlive state.

The MainWindow class has an object of type CellGrid. It renders the grid to the screen.

Edit 3:

XAML: http://pastebin.com/Zp3dr8zc

resources.xaml:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style TargetType="{x:Type MenuItem}">
        <Setter Property="HorizontalContentAlignment" Value="Center" />
        <Setter Property="VerticalContentAlignment" Value="Center" />
        <Setter Property="MaxHeight" Value="32" />
    </Style>
    <Style TargetType="{x:Type MenuItem}" x:Key="ParentMenuItem">
        <Setter Property="Width" Value="46" />
    </Style>
</ResourceDictionary>

回答1:


This is the result of using a DrawingContext/DrawingVisual. It's actually benign and should all be garbage collected as the system needs it, but the memory usage can be alarming. If you were to, instead, draw shapes on a canvas then you would probably not see this problem. I've run into this same issue with custom drawn controls in the past. Switching to more vector-based drawing techniques (i.e., shapes on a canvas) fixed the memory consumption problem.



来源:https://stackoverflow.com/questions/6449297/program-takes-too-much-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!