Creating the AsyncLock

Now that we have built the AsyncSemaphore class, we will use this object inside the AsyncLock object. Let's add a new file called AsyncLock.cs into the Threading folder and implement the following:

public class AsyncLock { private readonly AsyncSemaphore m_semaphore; private readonly Task<Releaser> m_releaser; public AsyncLock() { m_semaphore = new AsyncSemaphore(1); m_releaser = Task.FromResult(new Releaser(this)); } public Task<Releaser> LockAsync() { var wait = m_semaphore.WaitAsync(); return wait.IsCompleted ? m_releaser : wait.ContinueWith((_, state) => new Releaser((AsyncLock)state), this, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } public struct Releaser : IDisposable ...

Get Xamarin Blueprints now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.