Stylzs05
Stylzs05

Reputation: 521

Using the lock statement

I have a Bitmap that I'm trying to save and I keep getting the "Object is currently in use elsewhere" error. Now I know GDI+ sucks with threading and that I'm supposed to use the lock{} statement but it's not working. My code is below, what am I doing incorrectly?

Bitmap bitmap = new Bitmap();

lock (bitmap)
{
    bitmap.Save([filepath], ImageFormat.Png);
}

Upvotes: 2

Views: 1196

Answers (4)

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

You need to have lock around all operations, not just Save. Locking for just save will not block other threads from manipulating the Bitmap.

Note that it is better to lock on separate object as everyone recommends.

// class member (or even static) 
private object bitmapLock = new object();

// function 1
lock (bitmapLock)
{
    bitmap.Save([filepath], ImageFormat.Png);
}

// function 2
lock (bitmapLock)
{
   // Draw bitmap
}

Upvotes: 1

gdoron
gdoron

Reputation: 150253

You should lock other dummy object:

var objectForLock = new object()

lock (objectForLock)
{
    Bitmap bitmap = new Bitmap();
    bitmap.Save([filepath], ImageFormat.Png);
}

Not sure if that's your problem, but that's the way lock works in .Net.

Upvotes: 3

Daniel A. White
Daniel A. White

Reputation: 190945

You should not lock on the object you are trying to lock. You should create a new reference and lock on that instead.

object bitmapLock = new object();
Bitmap bitmap = new Bitmap();

lock (bitmapLock)
{
    bitmap.Save([filepath], ImageFormat.Png);
}

The bitmap might lock in different places that are beyond your control.

Read about the lock statement here.

Edit you might have to modify the bitmap on the thread that it was created.

http://msdn.microsoft.com/en-us/library/c5kehkcz(v=vs.80).aspx

Upvotes: 3

animaonline
animaonline

Reputation: 3804

You should lock synchronize before you initialize the Bitmap.

Upvotes: 2

Related Questions