Threading Design Tips

By | June 4, 2014

Threading is a valuable programming technique to make applications more scalable and responsive. Weather you are aware of it or not, it is likely that the programs you are writing are using some aspect of threading – this is particularly true of web applications where web page requests are handled by a thread pool in the web server. Programming in a threaded environment requires experience and care to avoid issues such as deadlocking and race conditions. The threading knowledge pack is designed to help you create thread-safe code easily so your software is more responsive and scalable.

Protect Static Data with Thread Synchronization: Static data should be effectively protected from possible threading issues by using appropriate synchronization methods. Avoid calling static methods that call static methods on the same class: Performance issues can result when a static method in class calls another static method in the same class. Avoid providing static methods that alter static state: Avoid providing static methods that alter static state. Static state is shared across threads which means multiple threads can execute that code at the same time opening up the possibility for threading bugs. Use thread pooling classes to optimize multi-threaded applications: Avoid using System.Threading.Thread class to create threads unless you have special needs. Instead usage of system thread pool (ThreadPool class) can improve your performance and scalability.

Do not terminate other threads using Thread.Abort: Avoid calling Thread.Abort method, instead use Thread.Join to wait until desired thread finishes. Excessive use of thread synchronization: Excessive locking or thread synchronization can cause significant scalability and performance issues and should be minimized Ensure lock release by using try/finally block: When using Monitor to synchronize your static data, you should ensure adequate release of the lock under any circumstance by using try/finally blocks.

Lock Must not be Obtained on a Value Type: Montor.Enter() and Exit() calls must lock on a reference type (in other words an object). They should never lock on a value type such as “int”.

Leave a Reply