I encounterd TextureBrush OutOfMemoryException with .NET Compact Framework 2.0.
Environment:
Visual Studio 2005 Team Suite / Japanese version.
.NET Compact Framework 2.0 Service Pack 1
Sharp W-ZERO3 WS004SH for the target machine.
By using TextureBrush with extensive FillPolygon results in OutOfMemoryException.
Forcing GC does not help.
I used the using pattern, and those instances should have no leak.
If I replace
g.FillPolygon(textureBrush, drawArea);
with g.FillRectangle(textureBrush, 0,0,100,100);
then, it works fine.
Therefore, it could be a potential bug of .NET Compact Framework 2.0.
I have checked out the same symptom by the Google and found a few people reported same issue.
But, there seems to be no solution yet.
—————–
// Run following code and wait for a few minutes, then results in the exception.
// Please note that you have to add a timer with 100mSEC interval and enabled state.
—————–
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace TextureBrushOutOfMemory1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
this.Invalidate();
}
private Bitmap backBuffer = null;
Point[] drawArea = { new Point(10, 10), new Point(90, 10), new Point(90, 90), new Point(10, 90) };
Bitmap bmp = null;
Random rnd = new System.Random();
private void Form1_Paint_1(object sender, PaintEventArgs e)
{
using (Graphics g = e.Graphics)
{
doPaint(sender, g);
}
}
private void doPaint(object sender, Graphics gr)
{
// Make a new back buffer if needed.
if (backBuffer == null)
{
backBuffer = new Bitmap(this.ClientSize.Width, this.ClientSize.Height);
}
if (bmp == null)
bmp = new Bitmap(100, 100);
// Create Image for TextureBrush
using (Graphics g = Graphics.FromImage(bmp))
using (SolidBrush redBrush = new SolidBrush(Color.Red))
using (SolidBrush blueBrush = new SolidBrush(Color.Blue))
{
float val = 0.5F;
g.FillRectangle(redBrush, 0, 0, 100, 100);
for (int i = 0; i < rnd.Next(300); i++)
{
g.FillRectangle(blueBrush, (int)(val * rnd.Next(100)), 100 – (int)(val * rnd.Next(100)), (int)(val * rnd.Next(50)), (int)(val * rnd.Next(50)));
}
}
// FillPolygon on the backBuffer with textureBrush
using (Graphics g = Graphics.FromImage(backBuffer))
using (TextureBrush textureBrush = new TextureBrush(bmp))
{
g.FillPolygon(textureBrush, drawArea);
// g.FillRectangle(textureBrush, 0,0,100,100);
// FillRectangle works fine.
// But, FillPolygon results in Out of Memory Exception.
}
// Force GC by GC.Collect() or WaitForPendingFinalizers() is not effective.
GC.Collect();
GC.WaitForPendingFinalizers();
// Draw the backBuffer to the FormWindow
gr.DrawImage(backBuffer, 0, 0);
}
protected override void OnPaintBackground(PaintEventArgs pevent)
{
// avoid flicker
}
private void button1_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}