InvalidOperationException – Das Objekt wird bereits an anderer Stelle verwendet

Heute hatte ich einen Fehler in meinem Programm beim Zugriff auf ein Bitmap von einem Hintergrund-Thread aus:

InvalidOperationException – Das Objekt wird bereits an anderer Stelle verwendet.

Auf Englisch:

InvalidOperationException – object is currently in use elsewhere.

Die Ursache ist ein Zugriff von mehreren Threads aus auf dasselbe Bitmap-Objekt.

Auf Stack Overflow schreibt Hans Passant die Lösung:

There’s a lock inside GDI+ that prevents two threads from accessing a bitmap at the same time. This is not a blocking kind of lock, it is a „programmer did something wrong, I’ll throw an exception“ kind of lock. Your threads are bombing because you are cloning the image (== accessing a bitmap) in all threads. Your UI thread is bombing because it is trying to draw the bitmap (== accessing a bitmap) at the same time a thread is cloning it.

You’ll need to restrict access to the bitmap to only one thread. Clone the images in the UI thread before you start the BGWs, each BGW needs its own copy of the image. Update the PB’s Image property in the RunWorkerCompleted event. You’ll lose some concurrency this way but that’s unavoidable.

Ich muss also sicherstellen, dass auf ein Bild-Objekt nur von einem Thread aus zugegriffen wird.