title: Managing user operations synchronization on Azure Cloud Service
body: <p>I have <code>.net4.5</code> <code>WebRole</code> project running on local <code>IIS</code> (dev purposes) and on <code>Azure</code> as <code>Cloud service</code>.</p>
  
  <p>This project is handling request from users. Requests for one user can came from many clients types, for example from <code>WWW</code> (another project hosted on <code>IIS</code> and <code>Azure</code>), <code>android app</code> and <code>windows application</code>. There is one layer which translates each request type to some general request with <code>User</code> as parameter. <code>User</code> is an entity.</p>
  
  <p>To communicate with database (<code>MS SQL EXPRESS</code> or <code>AzureSQL</code>) I'm using <code>EntityFramework</code>.</p>
  
  <p>The problem is with synchronization. I'd like to have synchronized request handling per user. There could be thousands of users, some not active, some hardly ever active and some active all the time. I want to avoid slowdown caused by some mutexes.</p>
  
  <p>This code would probably work, but will be extremely slow:</p>
  
  <pre><code>private Object allUsersMutex = new Object();
  private Dictionary&lt;long, Object&gt; perUserMutex = new Dictionary&lt;long, Object&gt;();
  
  private Object getUserMutex (User user) {
      synchronized (allUsersMutex) {
          if (!perUserMutex.containsKey(user.ID)) {
              perUserMutex[user.ID] = new Object();
          }
          return perUserMutex[user.ID];
      }
  }
  </code></pre>
  
  <p>and then, on all methods I could get mutex by this method and synchronize on it.</p>
  
  <p>Is there any mechanism helping with something like this?</p>