在WP7中实现互斥和监视器芒果 [英] Implementing mutex and monitor in WP7 Mango

查看:217
本文介绍了在WP7中实现互斥和监视器芒果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

mutex和monitor实现之间有什么区别。任何一个请帮助我学习这些为wp7(可执行代码为wp7)。请尝试添加一些代码片段,帮助我以一种简单的方式了解这些技术。
Thanx提前
Stezma

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

推荐答案

互斥锁可以锁定多个进程。如果您的计划任务正在运行,需要对资源进行独占访问,这在Windows Phone中将非常有用。为了在进程之间锁定互斥体,必须为Mutex命名。

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示例:

手机应用任务:

   public class DatabaseService
    {
    private Mutex _mut=new Mutex("mutex control",false);
    public void AddToDatabase(DbObject row)
    {
        mut.WaitOne();
        SaveRow(row);
        mut.ReleaseMutex();
    }
    }

计划任务类:

 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();
    }
    }

在上面的例子中,一次访问本地数据库资源。这是为什么我们要使用Mutex。

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):

任务:

   public class DatabaseService
    {
    private object _locker=new object();
    public void AddToDatabase(DbObject row)
    {
        lock(_locker)
            SaveRow(row);
    }
    }

计划任务类:

 public class ResourceUtilisation
 {
    private object _locker=new object();
    //.. does stuff
    private static void UseResource()
    {

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

在这个例子中,我们可以停止多个应用程序线程进入SaveRow,我们可以停止多个ScheduledTask线程进入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.

这是基本上的区别。监视器也比Mutex快得多。

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

这篇关于在WP7中实现互斥和监视器芒果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆