I have done it:
private Bitmap bit;
private Graphics dc;
// Used to suspend layout
private delegate void Suspend(bool b);
private Suspend mySuspend;
private void SuspendLayoutDel(bool b)
{
if (b)
this.SuspendLayout();
else
{
this.ResumeLayout();
// Set to true to force full redraw
Invalidate(true);
}
}
private void SetPixel(Point xy, Color clr, Graphics dc)
{
Pen _pen = new Pen(clr, 1);
//Lock prevents accsess from other threads
lock(dc)
{
dc.DrawRectangle(\_pen, new Rectangle(xy, new Size(1, 1)));
}
\_pen.Dispose();
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if (bit == null)
{
bit = new Bitmap(300, 300);
dc = Graphics.FromImage(bit);
}
e.Graphics.DrawImage(bit,0,0);
}
private void button1_Click(object sender, EventArgs e)
{
// Asign delegate so that Invoke is useed (Threat Safety)
mySuspend = new Suspend(SuspendLayoutDel);
Thread th = new Thread(new ThreadStart(Dummy));
th.Name = "Drawer";
th.Start();
}
private void Dummy()
{
this.Invoke(mySuspend, new Object[]{true});
Random rnd = new Random();
int buff = 0;
for (int y = 0; y < 300; y++)
{
for (int x = 0; x < 300; x++)
{
buff = rnd.Next(0, 4);
if (buff == 0)
SetPixel(new Point(x, y), Color.Cyan,dc);
else if (buff == 1)
SetPixel(new Point(x, y), Color.Magenta, dc);
else if (buff == 2)
SetPixel(new Point(x, y), Color.Yellow, dc);
else if (buff == 3)
SetPixel(new Point(x, y), Color.Black, dc);
}
}
this.Invoke(mySuspend, new Object\[\] { false });
}
I used graphic to draw to bitmap. Aka to memory. After all is displayed, it draws on screen. This aproach is olmost instantly compared to draw directly to screen.