Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.7k views
in Technique[技术] by (71.8m points)

c# - Program takes too much memory

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...