Implementing mutex and monitor in WP7 Mango

2019-03-22 06:49发布

what is the difference between mutex and monitor implementation. Can any one please help me to learn both of these for wp7(implementable code for wp7). Please try to add some code snippets that help me to understand the techniques in a simple way. Thanx in advance Stezma

1条回答
甜甜的少女心
2楼-- · 2019-03-22 07:31

A mutex can lock across multiple processes. This would be useful in Windows Phone if you have a scheduled task running that needs exclusive access to a resource. In order to lock a mutex across processes the Mutex must be given a name.

A monitor can lock only within a process.

Mutex Example:

Phone App Task:

   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);
    //.. does stuff
    private static void UseResource()
    {
        // Wait until it is safe to enter.
        _mut.WaitOne();

        //Go get dataabse and add some rows
        DoStuff();

        // Release the Mutex.
        _mut.ReleaseMutex();
    }
    }

In the above example we're only allowing one app at a time access to the local database resource. This is why we'd use a Mutex.

Monitor Example (using lock syntax):

Phone App Task:

   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();
    //.. does stuff
    private static void UseResource()
    {

        //Go get dataabse and add some rows
        lock(_locker)
            DoStuff();
    }
 }

In this example we can stop more than one application thread entering SaveRow and we can stop more than one ScheduledTask thread from entering the DoStuff method. What we can't do with a Monitor is ensure that only one thread is accessing the local DB at once.

That's basically the difference. Monitor is much faster than a Mutex as well.

查看更多
登录 后发表回答