WriteableBitmap.Lock 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
保留後方緩衝區給更新。
public:
void Lock();
public void Lock();
member this.Lock : unit -> unit
Public Sub 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 方法會增加鎖的數量。 當 a WriteableBitmap 被鎖定時,渲染系統不會發送更新,直到 WriteableBitmap 透過呼叫 Unlock 方法完全解鎖。
你可以用這個 Lock 方法來支援多執行緒實作。 在這些情況下,UI 執行緒會鎖定位圖,並將後方緩衝區暴露給其他執行緒。 當工作執行緒完成一個框架後,UI 執行緒會新增變更的矩形並解鎖緩衝區。
當渲染執行緒取得後方緩衝區的鎖定時,UI 執行緒可以阻擋將它向前緩衝區複製。 如果這個區塊的延遲太長,可以用這個 TryLock 方法等一小段時間,然後在後方緩衝區鎖定時解除 UI 執行緒,讓它執行其他任務。