【发布时间】:2015-12-18 02:43:15
【问题描述】:
有一段时间,我在 C# 中使用 pictureBox 为模拟和其他事情做动画。现在我正在编写代码来攻击一个朋友(他只需要按 alt-f4 即可关闭它,没什么大不了的。)但我一直收到这个错误:
An unhandled exception of type 'System.OutOfMemoryException' occurred in System.Drawing.dll
Additional information: Out of memory.
代码:
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;
namespace EnrogSecurityBreach
{
public partial class Form1 : Form
{
Timer timer = new Timer();
Form1 form1;
//Bitmap bmp;
public Form1()
{
InitializeComponent();
form1 = this;
form1.TransparencyKey = Color.White;
FormBorderStyle = FormBorderStyle.None;
WindowState = FormWindowState.Maximized;
pictureBox1.Left = 0;
pictureBox1.Top = 0;
pictureBox1.Width = Screen.PrimaryScreen.Bounds.Width;
pictureBox1.Height = Screen.PrimaryScreen.Bounds.Height;
timer.Enabled = true;
timer.Interval = 10;
timer.Tick += timer_tick;
}
Random rand = new Random();
int partsection = 0;
int waitint = 0;
int ran1 = 0;
int ran2 = 0;
int intensifies = 0;
public void timer_tick(object e, EventArgs ea)
{
Bitmap bmp;
bmp = new Bitmap(pictureBox1.Width, pictureBox1.Height);
using (Graphics g = Graphics.FromImage(bmp))
{
if (partsection == -1)
{
}
else if (partsection<300)
{
if (waitint == 0)
{
ran1 = rand.Next(0, pictureBox1.Width);
ran2 = rand.Next(0, pictureBox1.Width);
waitint = 10;
}
else
{
waitint--;
}
g.FillRectangle(new SolidBrush(Color.Green), (float)ran1, (float)0, 3, pictureBox1.Height);
g.FillRectangle(new SolidBrush(Color.DarkGreen), (float)ran2, (float)0, 3, pictureBox1.Height);
partsection++;
}
else if (partsection < 1000)
{
if (intensifies < 255)
{
intensifies++;
}
else
{
}
g.FillRectangle(new SolidBrush(Color.FromArgb(intensifies,Color.Black)), (float)0, (float)0, pictureBox1.Width, pictureBox1.Height);
}
}
pictureBox1.Image = bmp;
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
感谢您的帮助。
【问题讨论】:
-
你在泄露
SolidBrushes,这是肯定的。你需要处理掉它们。我不确定的是您是否还需要明确处理旧的pictureBox1.Image图像。每秒 100 个滴答声也相当过分...... -
我需要更改哪些代码?不好意思,我只用c#写了半年左右。
-
您的
SolidBrush应该在using语句中,如您的Graphics或在单独的行中声明,以便您可以在 em 上调用Dispose。或者更好的是,在类级别声明它们并重复使用相同的画笔,而不是每次都创建一个新画笔。对于pictureBox,您可以查看this answer。您可以将Tick更改为 33 大约 30FPS,这应该足够流畅并且对硬件的负担更少。虽然不确定图片框。 -
好的,就像 SolidBrush sb1 = new SolidBrush(); //使用代码 sb1.Dispose();
-
更改代码以使用 3840x2160 的固定屏幕分辨率,它确实为我抛出了
OutOfMemoryException。所以显然它确实泄漏了,尽管是由于延迟触发的 GC(见下面的伊恩回答)。在pictureBox1.Image = bmp;之前添加if (pictureBox1.Image != null) pictureBox1.Image.Dispose();可能会解决内存不足的问题...
标签: c#