views:

148

answers:

1

I've got a WritableBitmap that updates on a separate thread, specifically in response to an event.

myWritableBitmap.Lock();
CopyMemory(myWritableBitmap.BackBuffer, ...);
myWritableBitmap.AddDirtyRect(...);
myWritableBitmap.Unlock();

When run on a separate thread as-is, the Lock() command throws a System.InvalidOperationException.

If I run the same code like this:

this.Dispatcher.Invoke(new VoidDelegate(delegate
{
  //Same code as above...
}));

No exceptions are thrown and the code runs perfectly. Wouldn't the purpose of the Lock() be to allow multi-threaded access? Any idea why this is happening?

+1  A: 

Many of the WPF drawing functions must run in a STAThread. The second piece of code makes your drawing functions run in the main UI thread.

Edit: A little bit more about threading in WPF found here.

HakonB
The lock shouldn't be doing any drawing though. I would assume I could copy the memory to the back buffer and then it would be drawn on the UI thread.
Will Eddins
I think the case is that it is that much of the drawing functionality found in WPF uses some COM-based code - which needs to be called from the a STAThread.
HakonB
Would this mean I could spawn the above code on a new thread with Apartment = STA?
Will Eddins