Motivation

On Windows Store and Windows Phone apps you cannot use the lock keyword for synchronizing access to a code block that contains one or several await calls.

How-to

This minimalistic Enough.AsyncLock tool helps you to synchronize access easily:

using Enough.Async;

namespace MyApp
{
  public class MyDataRetriever
  {
     private AsyncLock _asyncLock = new AsyncLock();

     public async Task<Data> GetData()
     {
        using (await _asyncLock.LockAsync())
        {
            Data data = await GetDataFromStorage();
            if (data == null)
            {
               data = await GetDataFromWeb();
               await StoreData(data);
            }
        }
        return data;
     }
   }
}

Installation

Install the Enough.AsyncLock NuGet package in the Package Management Console:

PM> Install-Package Enough.AsyncLock 

Alternatively right-click your project references, select "Manage NuGet Packages..." and search for "Enough.AsyncLock".




Last edited Oct 17, 2013 at 7:20 PM by enoughrob, version 4