Reshef’s tip of the day

.net development tips

Archive for the ‘multithreading’ Category

Tip of the day: Mutual exclusion when Remoting

Sunday, November 25th, 2007

Another tip from Gal:"

Just a small tip that might have saved me a few good hours:

A Mutex can be released only by the thread that originally locked it.

A semaphore can be released by any thread.

I used a mutex at the beginning, while locking and releasing on different threads, and at the threadpool desire, got ("sometimes" is the WORST one) an

ApplicationException - Object synchronization method was called from an unsynchronized block of code.

Usually this means that the mutex is not locked but still tries to be released – check this out.

But in my case (first remoting call locks an object and the second releases), it was just that a mutex was the wrong sync method, and a semaphore quickly solved the problem.

As mentioned in the link, the error message need some work."

Tip of the day: ThreadStatic attribute

Sunday, November 25th, 2007

According to the msdn documentation, the ThreadStatic attribute "Indicates that the value of a static field is unique for each thread."

A practical use for it can be a registrar implementation. A registrar can be used as a static entry point to store context data for say, a request that is being processed by several classes that need to share data.

Implementation example:

public static class Registrar
{
   [ThreadStatic]
   private static Dictionary<string, object>
      m_registrar = null;

   private static Dictionary<string, object>
      LocalDictionary
   {
      get
      {
         if (m_registrar == null)
         {
            m_registrar =
               new Dictionary<string, object>();
         }
         return m_registrar;
      }
   }

   public static object Get(string key)
   {
      return LocalDictionary[key];
   }

   public static void Set(string key, object value)
   {
      LocalDictionary[key] = value;
   }
}

Now since the m_registrar is marked with ThreadStatic attribute, is static per thread, which means that no locking is required and no data corruption can occur.

A real world example for using such strategy is HttpContext.Items

Gilad pointed out two important points:

- ASP.NET is changing threads under the hood so don’t use it there since u will most probably get your data corrupted. The HttpContext knows how to handle that so use it.

- When using a thread pool, the threads are not killed and so when a thread completes execution and returned to the pool, the static data is still kept. In this case u should use an execution wrapper than clears the per thread static data after the thread complete execution.

Tip of the day: Interlocked

Sunday, November 25th, 2007

The Interlocked class in .net is a static class that provides type operation that are performed atomically.

By providing this, it can help solve simple multithreading scenarios since:

1) It removes the chance of deadlocks that can be caused by using the lock keyword.

2) It has better performance than the lock keyword.

3) Simpler (and less) syntax.

Lets take a look at a scenario where you would like to count how many times a method is called while a program runs (multithreaded environment):

private static int methodCallsCounter = 0;
…

public void SomeMethod()
{
    System.Threading.Interlocked.
        Increment(ref methodCallsCounter);
    …
}

The Interlocked class has a set of methods to manipulate data. A complete documentation and a full example can be found here.

Talking about multithreading and locks, I suggest reading this. It describes very important points about locking.

Jajah is the VoIP player that brought you web-activated telephony.