Using the lock statement

耗尽温柔 提交于 2019-12-13 16:23:32

问题


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);
}

回答1:


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.




回答2:


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




回答3:


You should lock synchronize before you initialize the Bitmap.




回答4:


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
}


来源:https://stackoverflow.com/questions/10587844/using-the-lock-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!