Wednesday, November 19, 2008

C# – How do you synchronize your methods?

Do you use the following pattern to synchronize your methods?

class Transaction 
{
   private static DateTime timeOfLastTransaction;
   public static void PerformTransaction() {
      lock (typeof(Transaction)) {
         timeOfLastTransaction = DateTime.Now;
      }
   }
   public static DateTime LastTransaction {
      get { 
         lock (typeof(Transaction)) {
            return timeOfLastTransaction;
         }
      }
   }
}

The above is probably what a majority of C# programmers write (I did too for a long time). This is because this was how Microsoft said we should. (Instead of using the type object you might be using the this reference for the lock).

Well if you don’t know this by now – the above method is not the best way to synchronize your methods because the object on which your locking is public and could be locked by code run out side of the class.

The correct way to perform synchronization is to use an object whose raison d'etre is to provide synchronization.

class Transaction {
   // Private, static Object field 
   // used purely for synchronization
   private static Object objLock = new Object();

   private static DateTime timeOfLastTransaction;
   public static void PerformTransaction() {
      lock (objLock) {
         timeOfLastTransaction = DateTime.Now;
      }
   }
   public static DateTime LastTransaction {
      get { 
         lock (objLock) {
            return timeOfLastTransaction;
         }
      }
   }
}

Read more about this topic in this MSDN article: http://msdn.microsoft.com/en-us/magazine/cc188793.aspx

(The above code snippets are based on the code snippets that appear in the above article)

No comments: