0

I've got some code which updates a WriteableBitmap being displayed in the UI, but on some machines the screen doesn't get updated after the 1st call to UpdateBmp; subsequent calls don't have any visible effect.

Any idea what I'm doing wrong? I've followed the guidelines for using a WriteableBitmap as I understand them:

  1. Call Lock() before making changes to the back buffer
  2. Call AddDirtyRect() between Lock() and Unlock()
  3. Call Unlock() when done making changes

The (simplified) XAML is just an Image control:

<Image x:Name="imgpreview" Margin="8" />

The (simplified) image update code looks like this:

WriteableBitmap bmp = null;
// Simplified version just paints the whole bitmap with a solid color
unsafe void UpdateBmp(int c)
{
    if (null == bmp)
        bmp = new WriteableBitmap(640, 480, 96.0, 96.0, PixelFormats.Pbgra32, null);

    bmp.Lock();
    try
    {
        for (int y = 0; y < bmp.PixelHeight; ++y)
            for (int x = 0; x < bmp.PixelWidth; ++x)
            {
                var pwrite = bmp.BackBuffer + y * bmp.BackBufferStride + 4 * x;
                *(int*)pwrite = c;
            }
     }
    finally
    {
        bmp.AddDirtyRect(new Int32Rect(0, 0, bmp.PixelWidth, bmp.PixelHeight));
        bmp.Unlock();
    }
    imgpreview.Source = bmp;
}

Again, it works repeatedly on one of my development machines, but the other machine only updates the image once. No exceptions are thrown, and I've verified through the debugger that the code is being called multiple times even though only the 1st result is displayed.

RogerN
  • 3,761
  • 11
  • 18
  • 1
    Maybe this is helpful: https://stackoverflow.com/q/33283077/1136211. Be aware that the Lock/AddDirtyRect/Unlock sequence only makes sense when you update the BackBuffer from a different thread. Here you may as well just call WritePixels. – Clemens Oct 03 '22 at 18:27
  • @Clemens Thanks, that looks relevant. The broken machine is using an Intel Graphics driver, but I'll need to do some more digging (and probably update the drivers) to confirm. – RogerN Oct 03 '22 at 18:41
  • It also turned out to explain this: https://stackoverflow.com/q/73831867/1136211 – Clemens Oct 03 '22 at 18:45
  • @Clemens Disabling hardware acceleration fixed the issue, so a driver issue seems likely. I won't be able to to update drivers until tomorrow. Thanks again for your input. – RogerN Oct 03 '22 at 20:39

0 Answers0