Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

c# - Locking does not prevent InvalidOperationException: Object is currently in use elsewhere

I was under the impression that lock() would prevent multiple threads from accessing an object simultaneously.

But, an InvalidOperationException (Object is currently in use elsewhere) is still frequently thrown by the following code:

lock (this)
{
    localCopy = (Bitmap)this.bm.Clone();
    int x, y;
    float pX = this.p.x;
    int width = localCopy.Width;
    x = (int)Math.Round((double)(pX * (float)width));
    if (x >= localCopy.Width) x = localCopy.Width - 1;
    y = (int)Math.Round((double)(this.p.y * (float)localCopy.Height));
    if (y >= localCopy.Height) y = localCopy.Height - 1;
    colourPixel = localCopy.GetPixel(x, y);
}

Some things to note:

  • I split up the calculation of x to isolate the cause of the exception. It appears to come from accessing the bitmap.
  • I tried creating a local copy of the bitmap, but this just causes the same exception. I've tried Clone()ing and creating a new Bitmap. Neither works.
  • I've tried locking on this (as seen) and on the bitmap object. Neither works.

Am I trying to use lock() in a way I'm not supposed to? Have I misunderstood it's purpose? How can I prevent InvalidOperationExceptions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Probably try using an object for locking purpose rather than locking "this".

A class level variable

private static object syncRoot = new Object();

and when you are using

lock (syncRoot)
{
....
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...