C# Mutex互斥锁

Mutex 构造函数 (Boolean, String, Boolean)

public Mutex (
    bool initiallyOwned,
    string name,
    out bool createdNew
)

参数

initiallyOwned

如果为 true,则给予调用线程已命名的系统互斥体的初始所属权(如果已命名的系统互斥体是通过此调用创建的);否则为 false

name

Mutex 的名称。如果值为 空引用(在 Visual Basic 中为 Nothing),则 Mutex 是未命名的。

createdNew        如果调用线程已被授予互斥体的初始所属权,则此方法返回时包含布尔值 true;否则包含布尔值 false。该参数未经初始化即被传递 一、当Mutex已存在的时候
static void Main(string[] args)
        {
            Thread th1 = new Thread(Thread1);
            Thread th2 = new Thread(Thread2);
            th1.Start();
            th2.Start();
            Console.ReadKey();
        }
        public static void Thread1()
        {
            bool bCreatedNewMutex;
            Mutex m = new Mutex(true, "HAHA", out bCreatedNewMutex);  //如果名为"HAHA"的互斥锁不存在,返回参数bCreatedNewMutex为true,否则为false
            if (bCreatedNewMutex)  //如果名为“HAHA”的互斥锁不存在
            {
                Console.WriteLine("th1装逼成功");
            }
            else
            {
                Console.WriteLine("th1装逼失败");
            }
        }
        public static void Thread2()
        {
            bool bCreatedNewMutex;
            Mutex m = new Mutex(true, "HAHA", out bCreatedNewMutex);
            if (bCreatedNewMutex)
            {
                Console.WriteLine("th2装逼成功");
            }
            else
            {
                Console.WriteLine("th2装逼失败");
            }
        }

二、使用了垃圾回收

static void Main(string[] args)
        {
            Thread th1 = new Thread(Thread1);
            Thread th2 = new Thread(Thread2);
            th1.Start();
            th2.Start();
            Console.ReadKey();
        }
        public static void Thread1()
        {
            bool bCreatedNewMutex;
            Mutex m = new Mutex(true, "HAHA", out bCreatedNewMutex);
            if (bCreatedNewMutex)
            {
                Console.WriteLine("th1装逼成功");
            }
            else
            {
                Console.WriteLine("th1装逼失败");
            }
        }
        public static void Thread2()
        {
            Thread.Sleep(1000);   //作用是等th1执行完毕,否则会报错:由于出现被放弃的 mutex,等待过程结束。
            GC.Collect();
            GC.WaitForPendingFinalizers();
            bool bCreatedNewMutex;
            Mutex m = new Mutex(true, "HAHA", out bCreatedNewMutex);
            m.WaitOne();
            if (bCreatedNewMutex)
            {
                Console.WriteLine("th2装逼成功");
            }
            else
            {
                Console.WriteLine("th2装逼失败");
            }
            m.ReleaseMutex();
        }

 



转载于:https://www.cnblogs.com/awaTangjay/p/6944540.html

你可能感兴趣的:(c#)