Search code examples
c#wpf.net-3.5artifactstearing

WPF: How do I prevent tearing with WriteableBitmap?


I'm using a WriteableBitmap to display images I process myself at around 20 frames per second.

This question (WPF: More efficient way of displaying quickly-changing images?)
and this question (How to display quick-updating images without large memory allocation?)
indicate that the best way to do this is by using a WriteableBitmap.

The documentation for WriteableBitmap indicates that calling WritePixels() on the UI thread will cause the rendering thread to redraw the image:

MSDN documentation:
The UI thread writes content to the back buffer. The render thread reads content from the front buffer and copies it to video memory. Changes to the back buffer are tracked with changed rectangular regions.

< snip / >

When updates are sent to the rendering thread, the rendering thread copies the changed rectangles from the back buffer to the front buffer. The rendering system controls this exchange to avoid deadlocks and redraw artifacts, such as "tearing".

I process my images on a background thread, then use Dispatcher.BeginInvoke() to call WritePixels(), to ensure that WritePixels() is called on the UI thread.

I'm finding that tearing still occurs with WriteableBitmap, and in the application I'm working on, it looks awful (its a medical imaging application). Is there anything I can do?


Solution

  • There was a lot of work put into WriteableBitmap to avoid tearing, but on some system configurations this is unavoidable. This mostly will happen on Windows XP or Vista w/ Aero (DWM) turned off.