For the complete documentation index, see llms.txt. This page is also available as Markdown.

Asynchronous Locks

Locker Synchronous and asynchronous mutex locks.

Locker is a lightweight mutex wrapper used to serialize critical sections in synchronous code and asynchronous code.

Both examples are taken from LockerTest; COUNT is the number of cycles of 500 defined in the fixture. The test verifies the mutual exclusion effect by concurrently incrementing the final count, rather than guessing the execution order with delays.

Synchronous Critical Section

The synchronization code uses Lock() to obtain a releasable lock handle, which is automatically released when leaving the scope of using.

Source: framework/Zongsoft.Core/test/Common/LockerTest.cs (excerpt; see source for context).

LockerTest.cs
public void Lock()
{
	var count = 0;
	var locker = new Locker();

	Parallel.For(0, COUNT, i =>
	{
		using(locker.Lock())
		{
			count++;
		}
	});

	Assert.Equal(COUNT, count);
}

Asynchronous Critical Section

Asynchronous code uses LockAsync() and releases the lock with await using.

Source: framework/Zongsoft.Core/test/Common/LockerTest.cs (excerpt; see source for context).

LockAsync supports cancellation tokens, which is suitable for background tasks that need to cancel waiting for locks.

If you need to create a change token, see Notification; if you need to express why the operation failed, see OperationException.

Last updated