October 7, 2008

Interlocked.CompareExchange Usage

To protect an area of code without blocking:
int m_InUse = 0;
...
// Only allow one thread to enter but do not queue up other threads
if (System.Threading.Interlocked.CompareExchange(ref m_InUse, 1, 0) == 0)
{  
  DoSomething();
  // No longer in use, reset it.
  // NOTE: Interlocked.Exchange not needed here as this is a write of a literal value!
  m_InUse = 0;
} 
Is semantically the equivalent of:
static object Lock = new System.Object();
public int CompareExchange(ref int loc, int value, int comp)
{
    Monitor.Enter(Lock);
    int ret = loc;
    if (ret == comp)  
        loc = value;
    Monitor.Exit(Lock);
    return ret;
}
although it does NOT use Monitors internally.
There is a good example of this being used in the Windows Service Class Example

No comments: