C#互斥锁Mutex类的用法

C#互斥锁Mutex类的简单用法

作用

C#中Mutex互斥锁,位于System.Threading命名空间中。
顾名思义,它是一个互斥的对象,同一时间只有一个线程可以拥有它,该类还可用于进程间同步的同步基元
如果当前有一个线程拥有它,在没有释放之前,其它线程是没有权利拥有它的。我们可以把Mutex看作洗手间,上厕所的人看作线程;上厕所的人先进洗手间,拥有使用权,上完厕所之后出来,把洗手间释放,其他人才可以使用。

用法

线程使用Mutex.WaitOne()方法等待C#Mutex对象被释放,如果它等待的C#Mutex对象被释放了,它就自动拥有这个对象,直到它调用Mutex.ReleaseMutex()方法释放这个对象,而在此期间,其他想要获取这个C#Mutex对象的线程都只有等待。
我们可以利用这个特性来控制一个应用程序只能运行一个实例(单例)。其他实例由于得不到这个Mutex而不能运行。

代码

代码如下所示:

using System;
using System.Threading;

public class App
{
    /// <summary>
    /// 程序启动时判断进程是否可以启动
    /// </summary>
    private App()
    {
        if (!CanCreate())
        {
            logger.Warn("Can't run the Environment now, because one Instance is already running!");
            Environment.Exit(-1);
        }
    }
    private static Mutex m_mutex;
    private static readonly string m_name = "";
    /// <summary>
    /// 进程是否可以创建
    /// </summary>
    /// <returns>是否可以创建</returns>
    private static bool CanCreate()
    {
        bool canCreate;
        m_mutex = new Mutex(true, m_name, out canCreate);
        return canCreate;
    }
}

这里先运行一个实例,然后再运行第二个,通过日志可以查看启动过程,如下所示:

2016-11-23 13:47:03 -[ Info]- App Info: PDT_Test_Environment v1.0.0
2016-11-23 13:47:03 -[ Info]- Application startup...
2016-11-23 13:47:05 -[ Warn]- Can't run the Environment now, because one Instance is already running!
2016-11-23 13:47:08 -[ Info]- Mutex PDT_Test_Environment was released. Application exit...

从日志可以看出,当第二个实例想运行的时候,由于已经有一个进程拥有了这个互斥锁,此进程不能拥有,所以进程启动被终止。
此外还需说明一点,mutexname是在系统中是唯一的,也就是上述代码中的Name,系统依靠这个name属性来标识唯一的Mutex

相关链接

原文链接:https://www.cnblogs.com/hitfredrick/p/6403014.html
相关文章链接参考:

  1. https://www.cnblogs.com/hsrzyn/articles/1588140.html
  2. https://blog.csdn.net/u012790165/article/details/79723537
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#中的互斥锁是一种同步机制,用于保护共享资源的并发访问。当一个线程拥有互斥锁时,其他线程无法同时拥有该锁,只能等待该线程释放该锁后才能获得。这样可以防止多个线程同时访问共享资源,避免数据竞争和不可预测的行为。 在C#中,可以使用System.Threading命名空间中的Mutex来创建互斥锁。下面是一个示例代码,演示了如何使用互斥锁来保护共享资源的访问: ``` using System; using System.Threading; public class Example { private static Mutex mutex = new Mutex(); // 创建互斥锁对象 public static void Main() { for (int i = 0; i < 5; i++) { Thread myThread = new Thread(new ThreadStart(MyThreadProc)); myThread.Name = String.Format("Thread{0}", i + 1); myThread.Start(); } } private static void MyThreadProc() { Console.WriteLine("{0} is waiting for the mutex", Thread.CurrentThread.Name); mutex.WaitOne(); // 等待互斥锁 Console.WriteLine("{0} has entered the critical section", Thread.CurrentThread.Name); // 访问共享资源 Console.WriteLine("{0} is leaving the critical section", Thread.CurrentThread.Name); mutex.ReleaseMutex(); // 释放互斥锁 } } ``` 在上面的示例中,创建了一个互斥锁对象mutex,并在MyThreadProc方法中使用mutex.WaitOne()等待互斥锁,使用mutex.ReleaseMutex()释放互斥锁。这样可以保证只有一个线程可以进入“critical section”,避免了多个线程同时访问共享资源的问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值