Hi
I try to draw onto bitmap inside a picturebox from multiple tasks. This is a simplified version of my main code. The purpose of this code is to draw onto a picturebox from multiple Tasks, since I will need to catch and draw with lines the position of my mouse on the pb and also graphically the readings from a sensor through a serial port. I keep on getting the error message: Object already in use elsewhere. Following other posts I have already tried to use the lock instruction, but I keep on getting this error message.
namespace TEst2
{
public partial class Form1 : Form
{
Bitmap bmp;
Graphics g;
public Form1()
{
InitializeComponent();
bmp = new Bitmap(pictureBox1.Width, pictureBox1.Height);
g = Graphics.FromImage(bmp);
}
private void pictureBox1_Click(object sender, EventArgs e)
{
pictureBox1.Image = bmp;
Task.Run( () => Draw());
Task.Run( () => DrawMouse());
Task.Run( () => DrawIt());
}
private void DrawIt()
{
while (true)
{
pictureBox1.Image = (Bitmap)bmp.Clone();
}
}
private void DrawMouse()
{
while (true)
{
try
{
lock (bmp)
{
BitmapData bmData2 = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat);
g.DrawLine(new Pen(Color.Green, 2), 50, 0, 50, 50);
bmp.UnlockBits(bmData2);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void Draw()
{
while (true)
{
try
{
lock (bmp)
{
BitmapData bmData2 = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat);
g.DrawLine(new Pen(Color.Red, 2), 0, 0, 50, 50);
bmp.UnlockBits(bmData2);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
}
I have noticed and also read in quiet a few posts that the problem seems to be rising, when using the pictureBox1.Image = bmp command. Thanks in advance for your help