Click or drag to resize
CanvasDeviceLock Method
Locks the device for the current thread.

Namespace:  Microsoft.Graphics.Canvas
Assembly:  Microsoft.Graphics.Canvas (in Microsoft.Graphics.Canvas.dll) Version: 0.0.0.0
Syntax
C#
public CanvasLock Lock()

Return Value

Type: CanvasLock
Remarks

If your application does not use multiple threads or Direct2D interop and only uses the default devices created by CanvasControl or CanvasAnimatedControl then you do not need to worry about any of the following!

Win2D takes care to ensure that methods on its API can be called from any thread. However, when sharing resources with non-Win2D APIs (using Direct2D interop or the interfaces from Windows.Graphics.DirectX.Direct3D11 for example) it is important to ensure these resources are only ever accessed from a single thread at a time.

This method allows you to take out a lock on the CanvasDevice so that only the current thread is able to access any Win2D resources created from that device. The returned object holds the lock until it is disposed.

For example, SoftwareBitmap.CreateCopyFromSurfaceAsync takes a reference to an IDirect3DSurface. Since SoftwareBitmap is not a part of Win2D it does not know that it needs to use Win2D's lock when accessing the surface. If the application had another thread running then these could both be accessing the underlying graphics device simultaneously. This code shows how to do this correctly:

SoftwareBitmap softwareBitmap;
using (var lock = canvasBitmap.Device.Lock())
{
    softwareBitmap = await SoftwareBitmap.CreateCopyFromSurfaceAsync(canvasBitmap);
}
If you are programming in C++/CX, the 'delete' keyword should be used to release the lock object.

Win2D is built on top of Direct2D, and inherits the threading model from there. The MSDN documentation can provide additional insight beyond the quick overview here.

In Direct2D terms, CanvasDevice.Lock calls ID2D1MultiThread::Enter and CanvasLock.Dispose calls ID2D1MultiThread::Leave.

See Also