title: What are the dangers of using Session.SyncRoot for locking per session?
body: <p>I have a race condition with the following code if two requests come in really close together in an ASP.NET MVC app:</p>
  
  <pre><code>var workload = org.Workloads.SingleOrDefault(p =&gt; ...conditions...);
  if (workload == null) {
      workload = org.CreateWorkload(id);
  }
  </code></pre>
  
  <p><code>workload</code> and <code>org</code> are EntityFramework objects. The call to <code>CreateWorkload</code> adds a row to a Workloads table in the database. (<em>We really should enforce this with a UNIQUE constraint on the table, but I can't now that the table has some dirty data in it.</em>) Subsequent calls to the Action method that contains this code throws an exception when <code>SingleOrDefault</code> encounters more than one row satisfying the conditions.</p>
  
  <p>So to fix this, I want to <code>lock</code> these lines of code. I don't want it done per request, with static lock object because that slows the site down for every user. What I'd like to do is use <a href="http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&amp;l=EN-US&amp;k=k%28SYSTEM.WEB.HTTPSESSIONSTATEBASE.SYNCROOT%29;k%28TargetFrameworkMoniker-%22.NETFRAMEWORK,VERSION=V4.0%22%29;k%28DevLang-CSHARP%29&amp;rd=true" rel="nofollow"><code>Session.SyncRoot</code></a> for locking. I.e.</p>
  
  <pre><code>Workload workload;
  lock (Session.SyncRoot) 
  {
      workload = org.Workloads.SingleOrDefault(p =&gt; ...conditions...);
      if (workload == null) {
          workload = org.CreateWorkload(id);
      }
  }
  </code></pre>
  
  <p>I'm not an ASP.NET expert, however, and there are some warning signs showing up in the docs and ReSharper, namely, that it can throw NotImplementedExceptions or be null. However, testing shows that this works just fine.</p>
  
  <p>So, ASP.NET experts, what are the risks of using Session.SyncRoot for this? As an alternative, if Session.SyncRoot is "really risky", could I assign a lock object in the Session collection on Session start up to do the same thing?</p>