使用命名互斥锁在appdomain之间同步 [英] Synchronizing between appdomains using named mutex

查看:88
本文介绍了使用命名互斥锁在appdomain之间同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在2个应用程序域之间进行同步,但是无法使其正常工作.

I want to sync between 2 appdomains, but can't get this to work.

我有这个:

static void Main(string[] args)
{
    using (Mutex m = new Mutex(true, "Global\\m"))
    {
        AppDomain ad = AppDomain.CreateDomain("ad");
        var dllName = new Uri(Assembly.GetExecutingAssembly().CodeBase).AbsolutePath;
        ad.CreateInstanceFrom(dllName, typeof(Consumer).FullName);

        Thread.Sleep(4000);
        m.ReleaseMutex();
    }

    Console.ReadLine();
}

public class Consumer
{
    public Consumer()
    {
        //var createdNew = false;
        //Mutex m = new Mutex(false, "Global\\m", out createdNew);
        Mutex m = Mutex.OpenExisting("Global\\m");
        m.WaitOne();
        Console.WriteLine("Done");
    }
}

我希望完成"会在4秒钟后打印出来,但是会立即打印出来.

I expect "Done" to be printed after 4 seconds, but it gets printed right away.

我尝试使用构造函数在消费者中创建互斥体,并使用OpenExisting-没什么区别. 在这种情况下,不要认为将互斥锁命名为"Global"不会有任何区别,但也可以尝试这样做.

I've tried creating mutex in consumer with constructor and using OpenExisting - makes no difference. Don't think naming mutex "Global" makes any difference in this case, but tried it too.

肯定会丢失一些东西,我不知道该怎么办.

Gotta be missing something, and I can't figure out what.. help?

推荐答案

互斥锁由线程拥有,并且它们是递归的,即可以在同一线程上再次输入.使用互斥锁可排除 other 线程,使其无法同时访问同一资源.您所要做的就是创建一个由调用线程拥有的互斥量,然后对其进行等待.由于该线程已经拥有该互斥锁,因此WaitOne立即返回.

A mutex is owned by a thread and they are recursive, i.e. can be entered again on the same thread. Use a mutex to exclude other threads from accessing the same resource simultaneously. All you've done is create a mutex owned by the calling thread and then waited on it. Since the thread already owns the mutex, WaitOne immediately returns.

要查看延迟,您必须在另一个线程上调用OpenExistingWaitOne.出于演示目的,您可以尝试以下方法:

To see a delay you would have to call OpenExisting and WaitOne on another thread. For demonstration purposes, you could try this:

public Consumer()
{
    Task.Run(() => {
        Mutex m = Mutex.OpenExisting("Global\\m");
        m.WaitOne();
        Console.WriteLine("Done");
    });
}

这篇关于使用命名互斥锁在appdomain之间同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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