The error arises because your UI thread uses the image (in particular, setting pictureBox.Image = someImage will cause the .NET ImageAnimator class to look on the image if it is to animate it (for animated. GIF- images, for example).
In the meantime, your background thread changes the image, which causes WinForms code to throw an exception "The object is currently being used elsewhere."
The following code works for me, never crashes, no matter how many threads I throw at it:
lock (locker) { using (Graphics gr = Graphics.FromImage(bmp2)) { gr.DrawImage(Resources.someImage, new Rectangle(0, 0, 800, 600)); pictureBox1.Invoke(new Action(() => pictureBox1.Image = bmp2)); } }
Shooting, it turns out, doesn't work either. Throw enough threads and it will work.
I suspect the problem is that Win32 draws your bitmap when the background thread draws on it. Read one (UI) stream, one (background) stream record. This will inevitably lead to problems.
The best solution for multi-threaded errors like this is often to stop exchanging data between threads. Instead, duplicate the data and let each thread have its own local copy. Here is an example:
lock (locker) { using (Graphics gr = Graphics.FromImage(bmp2)) { gr.DrawImage(Resources.someImage, new Rectangle(0, 0, 800, 600)); var clone = bmp2.Clone() as Image; pictureBox1.Invoke(new Action(() => pictureBox1.Image = clone)); } }
source share