Will Eddins
Will Eddins

Reputation: 13907

WritableBitmap does not work on separate Thread?

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?

Upvotes: 2

Views: 274

Answers (1)

HakonB
HakonB

Reputation: 7075

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.

Upvotes: 2

Related Questions