RAM使用率达到2 GB并在"`DrawImageUnscaled(b,0,0)`" - OutOfMemoryException

时间:2016-09-26 06:05:43

标签: c#

我有这段代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SharpDX.XInput;
using System.Threading;
using System.Reflection;
using System.Diagnostics;

namespace ControllerCheck
{
    public partial class CheckForm : Form
    {
        public CheckForm()
        {
            InitializeComponent();
        }

        Graphics x;

        private TimeSpan Redraw(object sender, EventArgs e)
        {
            var watch = Stopwatch.StartNew();
            Bitmap b = new Bitmap(DisplayPanel.Width, DisplayPanel.Height);
            Graphics g = Graphics.FromImage(b);
            g.FillRectangle(Brushes.White, 0, 0, DisplayPanel.Width, DisplayPanel.Height);
            g.FillRectangle(Brushes.Black, 0, 0, DisplayPanel.Width, DisplayPanel.Height);

            x.DrawImageUnscaled(b, 0, 0);
            watch.Stop();
            return watch.Elapsed;
        }

        private async void CheckForm_Shown(object sender, EventArgs e)
        {
            Task.Run(() =>
            {
                x = DisplayPanel.CreateGraphics();

                while (true)
                {
                    var ts = Redraw(null, null);
                    Console.WriteLine("Zajęło to {0} ticków, czyli {1} ms", ts.Ticks, ts.TotalMilliseconds); //(It tooked {0} ticks or {1} ms)
                }
            });
        }


    }
}

我想制作一个小程序,用SharpDX检查XInput

但是RAM的使用量达到2 GB并在" x.DrawImageUnscaled(b, 0, 0)"上抛出OutOfMemoryException。在Redraw(看截图)

我绘制白色和黑色矩形以查看它是否正常工作,它是,我只看到黑色矩形,因此RAM是唯一的问题

RAM usage goes to 2 GB and crashes on "<code>x.DrawImageUnscaled(b, 0, 0)</code>" - OutOfMemoryException

1 个答案:

答案 0 :(得分:1)

您需要使用Bitmap声明处理Graphicsusing

using (var b = new Bitmap(DisplayPanel.Width, DisplayPanel.Height))
using (var g = Graphics.FromImage(b))
{
    g.FillRectangle(Brushes.White, 0, 0, DisplayPanel.Width, DisplayPanel.Height);
    g.FillRectangle(Brushes.Black, 0, 0, DisplayPanel.Width, DisplayPanel.Height);

    x.DrawImageUnscaled(b, 0, 0);
}

由于Bitmap所占用的大部分内存都是不受管理的,因此一旦它被取消引用,您就不能指望GC及时为您清理它。它将最终,只是在没有使用托管内存的情况下才会尽快。