WriteableBitmap.Lock Method ()


The .NET API Reference documentation has a new home. Visit the .NET API Browser on docs.microsoft.com to see the new experience.

Reserves the back buffer for updates.

Namespace:   System.Windows.Media.Imaging
Assembly:  PresentationCore (in PresentationCore.dll)

public void Lock()

The Lock method increments the lock count. When a WriteableBitmap is locked, the rendering system does not send updates until the WriteableBitmap is fully unlocked by calls to the Unlock method.

You can use the Lock method to support multi-threaded implementations. In these scenarios, the UI thread locks the bitmap and exposes the back buffer to other threads. When the worker thread has finished a frame, the UI thread adds changed rectangles and unlocks the buffer.

The UI thread can block when the render thread acquires a lock on the back buffer to copy it forward to the front buffer. If the latency from this block is too long, use the TryLock method to wait for a short time and then unblock the UI thread to perform other tasks while the back buffer is locked.

The following code example shows how to reserve the back buffer by using the Lock method.

// The DrawPixel method updates the WriteableBitmap by using
// unsafe code to write a pixel into the back buffer.
static void DrawPixel(MouseEventArgs e)
    int column = (int)e.GetPosition(i).X;
    int row = (int)e.GetPosition(i).Y;

    // Reserve the back buffer for updates.

        // Get a pointer to the back buffer.
        int pBackBuffer = (int)writeableBitmap.BackBuffer;

        // Find the address of the pixel to draw.
        pBackBuffer += row * writeableBitmap.BackBufferStride;
        pBackBuffer += column * 4;

        // Compute the pixel's color.
        int color_data = 255 << 16; // R
        color_data |= 128 << 8;   // G
        color_data |= 255 << 0;   // B

        // Assign the color data to the pixel.
        *((int*) pBackBuffer) = color_data;

    // Specify the area of the bitmap that changed.
    writeableBitmap.AddDirtyRect(new Int32Rect(column, row, 1, 1));

    // Release the back buffer and make it available for display.

.NET Framework
Available since 3.0
Return to top