日期:2014-05-17  浏览次数:21137 次

互斥量 Mutex 疑问

   class MutexSample2
    {
        private static Mutex mutex = null;  //设为Static成员,是为了在整个程序生命周期内持有Mutex

        static void Main()
        {
            bool firstInstance;

            mutex = new Mutex(true, @"Global\MutexSampleApp", out firstInstance);
            try
            {
                if (!firstInstance)
                {
                    Console.WriteLine("已有实例运行,输入回车退出……");
                    Console.ReadLine();
                    return;
                }
                else
                {
                    Console.WriteLine("我们是第一个实例!");
                    for (int i = 60; i > 0; --i)
                    {
                        Console.WriteLine(i);
                        Thread.Sleep(1000);
                    }
                }
            }
            finally
            {
                //只有第一个实例获得控制权,因此只有在这种情况下才需要ReleaseMutex,否则会引发异常。
                if (firstInstance)
                {
                    mutex.ReleaseMutex();
                }
                mutex.Close();
           &nb