Search code examples
c#lockingwaithandle

When should I use a WaitHandle instead of a lock


In C#, when we should use WaitHandle instead of lock ?


Solution

  • A lock is fundamentally different from a WaitHandle. With a lock you write, for example:

    lock (SomeResource)
    {
        // do stuff here
    }
    

    The first line says, "I want exclusive access to that resource," and will wait until that resource is available (i.e. nobody else has a lock on it). Then the code runs and at the end the lock is released so that others can use it.

    WaitHandle is used to wait for some event to take place. When you write:

    MyWaitHandle.WaitOne();
    

    Your code is waiting for some other thread (possibly in a different process) to signal that WaitHandle. What it signals could be anything. Perhaps you're waiting for another thread to finish its job and say, "I'm done now," before your code can continue.

    So, to answer your question, you should use a lock when you want to gain exclusive access to a resource. You should use WaitHandle when you want to be notified of some event.