Multi Threading in C#

Threading in C#, by Joseph Albahari

Introduction to Multithreading in C#


The Santa Claus Problem – Thread Synchronization


thread safety

“A class is generally considered thread-safe if its methods can be invoked by multiple threads concurrently without corrupting the state of the class or causing unexpected side-effects. There are many reasons why a class may not be thread safe, although some common reasons are that it contains some state that would be corrupted on concurrent access.

There are a number of ways to make a class thread-safe:

Make it immutable, if a class contains no state it is safe to use concurrently from multiple threads.
Employ locking to reduce concurrency. However, this is no guarantee of thread safety, it just ensures that a block of code will not be executed concurrently by multiple threads. If state is stored between method invocations this might still become inconsistent.
How you create a thread-safe class really depends on what you want to do with the class in question.

You also need to ask yourself, do I need to make my class threadsafe? a common model of most UI frameworks is that there is a single UI thread. For example in WinForms, WPF and Silverlight the majority of your code will be executed from the UI thread which means you do not have to build thread-safety into your classes.”

Thread safety
“Thread safe: Implementation is guaranteed to be free of race conditions when accessed by multiple threads simultaneously.”

Race condition
“Race conditions arise in software when an application depends on the sequence or timing of processes or threads for it to operate properly. As with electronics, there are critical race conditions that result in invalid execution and bugs as well as non-critical race-conditions that result in unanticipated behavior. Critical race conditions often happen when the processes or threads depend on some shared state. Operations upon shared states are critical sections that must be mutually exclusive. Failure to obey this rule opens up the possibility of corrupting the shared state.

Race conditions have a reputation of being difficult to reproduce and debug, since the end result is nondeterministic and depends on the relative timing between interfering threads. Problems occurring in production systems can therefore disappear when running in debug mode, when additional logging is added, or when attaching a debugger, often referred to as a “Heisenbug”. It is therefore better to avoid race conditions by careful software design rather than attempting to fix them afterwards”



Proxy: Concurrency & Caches


Double checked locking


WCF Concurrency (Single, Multiple, and Reentrant) and Throttling