.NET Threading Interview Questions Series - Part 2

Q 21. What is the class hierarchy of wait handles?

waithandle class hierarchy

Q 22. What is ManualResetEvent and how it is different between AutoResetEvent?

ManualResetEvent is also a synchronization mechanism similar to AutoResetEvent which works on bool variable. If the bool variable is false, it blocks the thread. If true, it unblocks the threads.

ManualResetEvent provides the same methods as AutoResetEvent.

  1. WaitOne() : Blocks the current thread
  2. Set() : Unblock the current thread
  3. Reset() : Set the state of the event to non-signaled.

But AutoResetEvent unblocks only one thread at a time and ManualResetEvent unblocks all the waiting threads.

Another difference is that AutoResetEvent automatically called the Reset() method after unblocking the thread. But in case of ManualResetEvent, we must call the Reset() event manually.

Q 23. What is Semaphore?

AutoResetEvent is used for unblock only one thread. ManualResetEvent is used for unblock all the waiting threads.

But Semaphore gives you control how many threads you want to unblock at a time.

Q 24. How Semaphore works?

class Program
{
        static Semaphore semaphore = new Semaphore(5, 5);
        static void Main(string[] args)
        {
            Task.Factory.StartNew(() =>
            {
                for (int i = 1; i <= 15; ++i)
                {
                    PrintSomething(i);
                    if (i % 5 == 0)
                    {
                        Thread.Sleep(2000);
                    }
                }
            });
            Console.ReadLine();
        }

        public static void PrintSomething(int number)
        {
            semaphore.WaitOne();
            Console.WriteLine(number);
            semaphore.Release();
        }
}

When we create instantiate a semaphore object, we have to provide two parameters in the constructor. First one is the InitialCount and second one is MaximumCount.

MaximumCount denotes the maximum number of threads that can enter concurrently.

InitialCount denotes the initial number of threads which can enter the Semaphore directly.

Threads enter the semaphore by calling the WaitOne method and release the semaphore by calling the Release method. You can release multiple threads by passing the count in the Release method. By default Release method takes one and only release one thread.

Threading Interview Questions

Join our newsletter and get an occasional email with a technology and dotnetpattern.com news update.