【问题标题】:Mutex Constructor in .NET is strange?.NET 中的 Mutex 构造函数很奇怪?
【发布时间】:2012-08-01 07:56:41
【问题描述】:

我正在查看Mutex(Boolean, String) 页面,我完全糊涂了。如果我通过 true,我如何检查互斥锁是否归我所有或现在?然后我看到了Mutex(Boolean, String, out Boolean),可以使用第三个参数来检查。

我非常困惑。我测试过,如果另一个进程持有命名的互斥锁,新互斥锁不会返回 null 或抛出异常。但与其他我可以通过paran检查。那么构造函数和Mutex(Boolean) 的意义何在?

【问题讨论】:

    标签: .net constructor mutex


    【解决方案1】:

    如果你想创建一个 named 互斥体,但又不想拥有它,那么使用它似乎是理想的重载:

    如果name 不为空且initiallyOwnedtrue,则调用线程仅在此调用创建了命名系统互斥体时才拥有互斥体。 由于没有确定是否创建了命名系统互斥体的机制,因此在调用此构造函数重载时最好为initiallyOwned 指定false

    (强调)

    如果您使用 Mutex(Boolean) 构造函数,则会创建一个 本地 互斥体 - 在您的程序之外不可见。


    似乎这个类的设计者倾向于在构造函数重载中保持一致的参数顺序 - 有些人可能设计了这个特定的构造函数,根本没有 initiallyOwned 参数 - 只是使用 name。但这更多是一种风格选择。

    【讨论】:

    • 我认为这是“一致的参数排序”的原因。虽然我不明白为什么Mutex(bool) 会有用。
    【解决方案2】:

    Mutex(Boolean, String, out Boolean) 肯定总是不会返回 null,因为它和其他两个一样都是构造函数。构造函数永远不会返回 null。

    Mutex(Boolean, String) 用于几乎相同的原因,但如果您不想知道它是否由您创建,则例外。

    我相信Mutex(Boolean) 提供相同的功能,但有一个例外,即互斥锁是未命名的,并且仅在一个(您的)进程内共享。

    【讨论】:

      【解决方案3】:

      我相信答案在评论下方链接到的页面上

      If name is not null and initiallyOwned is true, the calling thread owns the mutex only if the named system mutex was created as a result of this call. Since there is no mechanism for determining whether the named system mutex was created, it is better to specify false for initiallyOwned when calling this constructor overload. You can use the Mutex(Boolean, String, Boolean) constructor if you need to determine initial ownership

      只有在您不关心是否真的成功获得所有权时,才应使用 2 args 构造函数。

      我承认有一个参数很奇怪,并建议只为所述参数传递一个值

      【讨论】:

        猜你喜欢
        • 2013-05-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-23
        • 1970-01-01
        • 2015-11-02
        相关资源
        最近更新 更多