All About Threads in .Net
Thread management has always been tricky especially from synchronization, locking and resource sharing perspective. At the same time avoiding dead locks is cumbersome. There are quite much features introduced in .Net that are available built-in to reduce effort required writing code from scratch. Not finding the material consolidated at one place, I decided to blog on them. I will be discussing those features one by one here:
Dot Net Thread Pool
Dot Net has provided a thread pool that can be used to execute our requests in multiple thread. It is quite a handy thread pool but it just provides basic functionality. What do I mean by that? I mean it just provides a queuing mechanism to queue up threads and executes these in a queue fashion. No other facility is provided like pause a thread, terminate a thread and most importantly prioritize a thread. Here is how you may use a Thread Pool:
In the above code, you are telling the threadpool to execute DisplayMessage method in a new thread. You should use ThreadPool.SetMaxThreads() and ThreadPool.SetMinThreads() to set the minimum and maximum limits for the threads.
If you would like to use smart thread pool, look at Smart ThreadPool available at:
Latest Smart Thread Pool can be downloaded from: (thanks Simon)
Asynchronous Method Calling
Often, it is required to call a method asynchronously. In order to achieve that we need to define delegates. Find below a snippet:
Have you ever heard about monitors. No ? No problem. In multi-threaded applications, the biggest challenge is to avoid execution of multiple threads on the same resource. One thing that could be used for that purpose is Monitor. Look at the following code snippet:
It’s been a nice synchronization technique available in .Net. Technically each object has a Monitor associated with it. We can also use Monitor without getting a lock on the shared resource.
NOTE: Just one suggestion, Monitor should be used almost always to make sure resource locking before performing operations on it.
Something About Mutex
We need to coordinate the activities of multiple threads (possibly across process boundaries) to
ensure the efficient use of shared resources or to ensure several threads are not updating the same
shared resource at the same time. Lets take a look at the following snippet using Mutex:
There are some business scenarios in which we need to limit the number of threads that can share concurrently some resource. We can do so by using Semaphore class provided by Dot Net. Look at the following code snippet, how we may achieve this:
Confused About Monitor, Mutex and Semaphore:
Monitor should be used in most of the circumstances to make sure resource is locked. Mutex is used for Inter-Process communication. Semaphores are used if a resource lock can be shared by limited number of threads.