Search code examples
c#.netwinformsgraphics

Control.Invalidate() use too much RAM. Optimization of C# WinForms drawing


I'm developing one game on WinForms on C# and i have a rotating drum of a revolver with cartridges. But my programm use over 2GB RAM. This is crazy. Even if i remove all code from OnPaint situation doesn't become much better. Probably exists smth another ways to update graphics

Spining logic:

int spinTimes = Global.rand.Next(12, 24);
int n = spinTimes * 20;
int mod = n / 25;
int delay = 10;
Thread spiningThread = new Thread(() =>
{
    for (int i = 0; i < n; i++)
    {
        if (i % mod == 0)
        {
            delay += 1;
        }
        if (wheelAngle + 3 < 360)
        {
            wheelAngle += 3;
        }
        else
        {
            wheelAngle = 3;
        }
        pictureBox1.Invalidate();
        Thread.Sleep(delay);
    }
});
spiningThread.Start();

OnPaint of pictureBox1:

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    Graphics g = e.Graphics;

    shots[] shots_arr = wheel.get();

    Point center = new Point(pictureBox1.Width / 2, pictureBox1.Height / 2);
    g.TranslateTransform(center.X, center.Y);
    g.RotateTransform(wheelAngle);
    g.TranslateTransform(-center.X, -center.Y);

    g.DrawImage(Image.FromFile("Images/wheel.png"),10,10,pictureBox1.Width - 15,pictureBox1.Height - 15);

    for(int i = 0; i < 6; i++) {
        Image image = null;
        switch (shots_arr[i])
        {
            case shots.EMPTY:
                {
                    image = Image.FromFile("Images/shot_empty.png");
                    break;
                }
            case shots.FULL:
                {
                    image = Image.FromFile("Images/shot_full.png");
                    break;
                }
        }
        if (image == null) { break; }
        g.DrawImage(image, shots_xy[i]);
    }
}

Solution

  • I used Windows Forms App (.NET Framework) instead of just Windows Forms App. Sorry for bothering. In case of just Windows Forms App i can spin my drum with any speed and this smooth and cost just 30mb of RAM. Thx everyone for help. You gave me a lot of good quastion how to better make graphics code and work with graphics at C#

    Image