Here is a small programming tip I thought I would share. Sometimes in .NET / C# I find myself needing to write a pattern similar to this:

private bool m_bSemaphore = false;

private void DoSomethingCrazy()
{
   if (m_bSemaphore == false)
   {
      m_bSemaphore = true;
      //Do some crazy stuff
      m_bSemaphore = false;
   }
}

This intent of this code would be to prevent the DoSomethingCrazy() method from being executed simultaneously.  The first thread to invoke DoSomethingCrazy() would set the semaphore and all subsequent calls from other threads would be ignored until the semaphore is reset. The problem with the code above is that it is not thread safe.  It is possible two competing threads could both execute the IF clause and decide the semaphore is false at exactly the same time.  The entire point of the semaphore is to prohibit this from happening, so the code above is actually a very subtle bug waiting to happen.  Most of the time it's going to work, but there is that small chance things are going to go wonky when least expected. A more robust solution which is thread-safe would be to craft the logic similar to this:

private object m_objSyncLock = new object();

private void DoSomethingCrazy()
{
   if (Monitor.TryEnter(m_objSyncLock))
   {
      //DoCrazyStuff
      Monitor.Exit(m_objSyncLock);
   }
}

By using the .NET static Monitor class makes we make the testing of the lock (TryEnter) and the acquisition of the lock into a single atomic operation (ie. only 1 thread can do both steps at a time).  

devMash.com Pinwheelarticle copyright © 2015 devMash.com

No Comments