A mutex can block multiple processes. This would be useful on Windows Phone if you have a scheduled task that requires exclusive access to the resource. To block a mutex through processes, Mutex must have a name.
The monitor can only be locked inside the process.
Mutex example:
The task of the application for the phone:
public class DatabaseService { private Mutex _mut=new Mutex("mutex control",false); public void AddToDatabase(DbObject row) { mut.WaitOne(); SaveRow(row); mut.ReleaseMutex(); } }
Scheduled task class:
public class ResourceUtilisation { private Mutex _mut=new Mutex("mutex control",true);
In the above example, we allow only one application to access the local database resource. That is why we will use Mutex.
Monitor example (using lock syntax):
The task of the application for the phone:
public class DatabaseService { private object _locker=new object(); public void AddToDatabase(DbObject row) { lock(_locker) SaveRow(row); } }
Scheduled task class:
public class ResourceUtilisation { private object _locker=new object();
In this example, we can stop more than one application that is part of SaveRow, and we can stop more than one ScheduledTask thread from entering the DoStuff method. What we cannot do with the monitor ensures that only one thread accesses the local database at once.
This is basically the difference. The monitor is much faster than Mutex.
source share