title: Locking multiple objects simultaneously
body: <p>In my code I have a method that handles transferring money from one account to another. Obviously, this method must make sure that only one transaction is being executed against each account at any given moment of program execution. I have implemented this check using 2 nested locks (<code>Account</code> is a DB entity aith a unique integer ID):</p>
  
  <pre><code>public void Transfer(Account from, Account to, decimal amount)
  {
      lock(GetLockObject(from))
      {
          lock(GetLockObject(to))
          {
              DoTransfer(from, to, amount);
          }
      }
  }
  
  private static Dictionary&lt;int, object&gt; lockObjects = new Dictionary&lt;int, object&gt;();
  private static GetLockObject(Accont acc)
  {
      lock (lockObjects)
      {
          var lockObject = lockObjects[acc.Id];
          if (lockObject == null)
          {
              lockObject = new object();
              lockObjects[accId] = lockObject;
          }
          return lockObject;
      }
  }
  </code></pre>
  
  <p>This seems to work fine but I have 2 concerns:</p>
  
  <ul>
  <li>The code can cause a deadlock if the method is called simultaneously with the same 2 accounts as its arguments: <code>Transfer(acc1, acc2, 10);</code> <code>Transfer(acc2, acc1, 10);</code> How do I avoid a deadlock here?</li>
  <li>Can the same result be achieved in a better way (in terms of performance, reliability, etc) than using nested locks?</li>
  </ul>