dotnet / dotnet/wpf

Flickering when updating WritableBitmap

Open
#11,025 11 comments 0 reactions 0 assignees View on GitHub
Question
Dominant language
C#
Stars
7.7k
Forks
1.3k
Avg merge
1d 11h
Merged PRs (30d)
61

Description

I'm developing a large-scale application with a custom rendering system. The system has a dedicated rendering thread that draws a specific region of a virtual canvas into a temporary memory buffer. Then, in the `OnRender()` method, I use `WritableBitmap.WritePixels()` to update the image content, and draw it to a specified screen region using `DrawingContext.DrawImage()`

During user interactions such as mouse dragging, the draw region changes in real time, but the actual image content is not necessarily updated on every `OnRender()` call.

I've noticed that occasionally, the image content does not match the drawn region, resulting in visible "jumps" or flickering during dragging. This issue is especially noticeable on my 4K display with integrated graphics, full-screen window, where the flickering happens frequently.

Interestingly, I encountered the same issue when previously using `InteropBitmap`, which also involves a updating image data mechanism. This leads me to believe the issue is related to how images with such updating mechanisms.

When I switched to creating a new `BitmapSource` in every 'OnRender()' call and drawing it directly—without using `WritableBitmap`—the issue disappeared entirely. This strongly suggests that `WritableBitmap.WritePixels()` is not synchronized with the `OnRender()` pipeline under certain conditions.

I also tried using `Dispatcher.Invoke` with `DispatcherPriority.Render` to call `WritePixels()`, but the problem persists.

It seems that under heavy rendering load, the image updated by `WritePixels()` might not be synchronized with the draw operation in `OnRender()`, leading to this visual mismatch.

How can I avoid this timing issue while still using `WritableBitmap`?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.