What is the difference between lock and Mutex?

Viewed 78251

What is the difference between lock and Mutex? Why can't they be used interchangeably?

8 Answers

Few more minor differences which were not mentioned in the answers:

  1. In the case of using locks, you can be sure that the lock will be released when an exception happens inside the lock's block.
    That's because the lock uses monitors under the hood and is implemented this way:

     object __lockObj = x;
     bool __lockWasTaken = false;
     try
     {
         System.Threading.Monitor.Enter(__lockObj, ref __lockWasTaken);
         // Your code...
     }
     finally
     {
         if (__lockWasTaken) System.Threading.Monitor.Exit(__lockObj);
     }
    

    Thus, in any case, the lock is released, and you don't need to release it manually (like you'd do for the mutexes).

  2. For Locks, you usually use a private object to lock (and should use).
    This is done for many reasons. (More info: see this answer and official documentation).

So, in case of locks, you can't (accidentally gain) access to the locked object from the outside and cause some damage.
But in case of Mutex, you can, as it's common to have a Mutex which is marked public and used from anywhere.

The Lock and Monitors are basically used to provide thread safety for threads that are generated by the application itself i.e. Internal Threads. On the other hand, Mutex ensures thread safety for threads that are generated by the external applications i.e. External Threads. Using Mutex, only one external thread can access our application code at any given point in time.

read this

Related