c# - 使用互斥锁来锁定对象

标签 c# object mutex

我有一个应用程序创建了一个需要锁定的对象,因为该对象创建了一个外部硬件设备对象(通过第三方 DLL),并且该硬件设备对象只能创建一次。当启动此应用程序的多个实例时,只有第一个实例应该能够创建此 C# 对象。子序列实例应该看到该对象已被锁定并且无法创建对象。我使用了互斥体,因为此对象创建发生在多个应用程序实例(多个进程)中。但是,代码不会使用互斥体锁定。我是否正在运行多个实例,其中每个实例都创建自己的锁?

public sealed class MyObject
{
    private static MyObject _myObject;
    static ExtDeviceDriver devDrv;
    private readonly static Mutex mut = new Mutex();

    private MyObject()
    {
        mut.WaitOne();
        //Thread safe code here.
        devDrv = new ExtDeviceDriver();
    }

    ~MyObject()
    {
        mut.ReleaseMutex();
    }

    // object accessor
    public static MyObject GetMyObject
    {
        get
        {
            if (_myObject == null)
                _myObject = new MyObject();
            return _myObject;   
        }
    }
}

最佳答案

我想你应该使用命名互斥体(See this article on MSDN)。

Mutexes are of two types: local mutexes and named system mutexes. If you create a Mutex object using a constructor that accepts a name, it is associated with an operating-system object of that name. Named system mutexes are visible throughout the operating system and can be used to synchronize the activities of processes. You can create multiple Mutex objects that represent the same named system mutex, and you can use the OpenExisting method to open an existing named system mutex.

所以,尝试使用这个constructor创建一个命名的互斥体。此外,您应该检查它是否已经存在 Mutex.OpenExisting Method (考虑这篇文章中给出的示例;它告诉我们如何检查、创建、利用命名互斥体)。

编辑

参见Mutex Class :

You can use the WaitHandle.WaitOne method to request ownership of a mutex. The thread that owns a mutex can request the same mutex in repeated calls to WaitOne without blocking its execution. However, the thread must call the ReleaseMutex method the same number of times to release ownership of the mutex. The Mutex class enforces thread identity, so a mutex can be released only by the thread that acquired it.

Mutex Constructor (Boolean, String) ,也就是说,必须将 bool 参数设置为:

true to give the calling thread initial ownership of the named system mutex if the named system mutex is created as a result of this call; otherwise, false.

关于c# - 使用互斥锁来锁定对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12469061/

相关文章:

c# - 读取xml时应该什么时候使用xml schemas(.xsd)?

java - 这段代码的作用是什么(曾经见过没有引用变量的对象吗?稍后在没有引用变量的情况下调用该对象怎么样?)?

c++ - 非递归互斥所有权

linux - 公平临界区 (Linux)

c# - 如何处理 MVC 中的 2 对 1 关系?

c# - 如何反序列化使用未指定和可变属性名称的 JSON 对象

c# - 从 JSON.net 中的 JArray 获取值

java - 小程序到对象标签

javascript - 使用动态输入删除 Javascript 中的一个项目

windows - Windows 中每个进程/线程的最大互斥量