Thursday, June 14, 2012

Lock on an integer in C#

There are times when you need thread synchronization based on values, may be on customer id or profile id, what we need to is to do thread synchronization base on value types is create a unique object per value to pass it on lock statement. Following is a simple implementation of value type synchronization.
 
Note: Visit http://coresystem.codeplex.com to download other synchronization classes

 public class SyncValue<T> where T :struct
{
     private Dictionary<T, object> syncObjects = new Dictionary<T, object>();

 
  public object GetObject(T value)
     {
         lock (this.syncObjects)
         {
             object syncObject;
             if (!this.syncObjects.TryGetValue(value, out syncObject))
                 this.syncObjects.Add(value, syncObject = new object());

             return syncObject;
         }
     }
}
 
 

Usage:

private static readonly SyncValue<int> syncValue = new SyncValue<int>();
// ...
lock (syncValue.GetObject(19))
{

   // ...

}

Although its good enough implementation but there is a draw back; once the object is create on particular id it will never be collected by GC. So here is a little bit different implementation of synchronization that should be find for very large set of customers data. As soon as the using block ended, sync lock will release lock and make sure to release the lock object base on lock counts.

 

Usage:

private static readonly SyncLock<int> sync = new SyncLock<int>();
// ...
using (sync.Lock(19))
{

   // ...

}

 

No comments:

Post a Comment