Implementing mutex and monitor in WP7 Mango

一曲冷凌霜 提交于 2019-12-21 03:01:15

问题


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:


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.



来源:https://stackoverflow.com/questions/7637183/implementing-mutex-and-monitor-in-wp7-mango

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!