WriteableBitmap.Lock 方法

定义

保留后台缓冲区用于更新。

public void Lock();

示例

下面的代码示例演示如何使用 Lock 方法保留后台缓冲区。

    // 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;

        try{
            // Reserve the back buffer for updates.
            writeableBitmap.Lock();

            unsafe
            {
                // Get a pointer to the back buffer.
                IntPtr pBackBuffer = 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));
        }
        finally{
            // Release the back buffer and make it available for display.
            writeableBitmap.Unlock();
        }
    }

注解

方法 Lock 递增锁计数。 WriteableBitmap锁定 时,呈现系统不会发送更新,WriteableBitmap直到 通过调用 Unlock 方法完全解锁 。

可以使用 Lock 方法支持多线程实现。 在这些方案中,UI 线程会锁定位图,并将后台缓冲区公开给其他线程。 当工作线程完成帧时,UI 线程会添加更改的矩形并解锁缓冲区。

当呈现线程在后台缓冲区上获取锁以将其向前复制到前缓冲区时,UI 线程可以阻止。 如果此块的延迟太长,请使用 TryLock 方法等待一小段时间,然后在锁定后台缓冲区时取消阻止 UI 线程执行其他任务。

适用于

产品 版本
.NET Framework 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10

另请参阅