title: Azure web job - Implementing mutual exclusion in the cloud
body: <p>we are looking at building a system which has an area of code that requires mutual exclusion. In a dedicated hosting environment on a single server we might use this simple code that would run on multiple threads:</p>
  
  <pre><code>SomeAsyncOperation();
  lock(locker)
  {
    SomeSyncOperation1();
    SomeSyncOperation2();
  }
  </code></pre>
  
  <p>Will this work in the cloud (assuming that webjobs may run across multiple physical machines)? Specifically Azure. If not how would this be implemented? So far I've looked at <a href="https://msdn.microsoft.com/en-us/library/microsoft.windowsazure.storage.blob.cloudblockblob.aspx" rel="nofollow">CloudBlockBlob</a> and the <a href="https://msdn.microsoft.com/en-gb/library/dn568101.aspx" rel="nofollow">competing consumer pattern</a>. What are people doing to achieve this?</p>
  
  <p>Thanks in advance.</p>
  
  <p>Edit: more info</p>
  
  <p>Operation1 performs a lookup on a table, then Operation2 adds an entry to both a queue and a table if Operation1 finds nothing (otherwise an exception is thrown). To prevent duplicate items being added to a queue it is important that Operation1 and Operation2 run atomically across all threads (the application is running using async/await).</p>
  
  <p>The following scenario is an example of how a race condition can emerge:</p>
  
  <pre><code>T1        T2
  O1()      
            O1()
            O2()
  O2()
  </code></pre>
  
  <p>On thread T1 operation1 has not found a duplicate. Thread T2 comes along and adds a duplicate. Threat T1 then runs operation2, which it should not have done.</p>
  
  <p>Normally this could be prevented using a lock(), but I don't believe this will work across physical machines (such as in the cloud). Unless I'm wrong about this...</p>