C#: Threading

Threading
 
– Avoid providing static methods that mutate static data—this opens up the possibility for threading bugs.
– Avoid taking locks if possible; Design your library with consideration for the stress of running in a server.
– Be aware that instance state does not always need to be thread-safe, Synchronized() and IsSynchronized() methods.
– Make all static state must be thread-safe—static data is shared across requests.
– Be aware of non-atomic operations—addressing this issue by taking an internal lock tends to be prohibitively expensive.
– Be aware of method calls in locked sections—this will cause a deadlock under heavy threading stress.
– Excessive use of fine-grained synchronization might negatively impact on performance and scalability.
– Consider using System.Threading.Interlocked for simple atomic updates—it’s tempting to use the C# lock statement.
  Consider using an interlocked compare exchange to update x only if it is still null.
  // Prefer using Interlocked.Increment(myFields);
  lock(syncRoot)
  {
     myFields++;
  }
  // Prefer using Interlocked.CompareExchange(ref x, rhs(), null));
  if (x == null)
  {
     lock(syncRoot)
     {
        x = rhs();
     }
  }
– The best practice is to create an object solely for the purpose of lock.
  public Class A {
     private Object thisLock = new Object();
     lock(thisLock) { … }
  }
– lock(this), lock(typeof(MyType), or lock("myLock") is a problem if they are publicly accessible and interned.
– Avoid locking at a too low level; consider having thread- safety to be the caller’s responsibility.
– Consider using a regular lock, Interlocked.Exchange(), or the ReaderWriterLock class.
– Use ThreadPool for the best performance instead of creating and managing your individual threads.
– Avoid creating architectures that requires developers to deal with threading or concurrency issues;
  Wherever possible, try to have the infrastructure handle threading complexities and well documented about sharing scenarios.
– Avoid the need for synchronization if possible—the algorithm can be adjusted to tolerate races rather than eliminating them.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s