C# FrameworkAPI之Mutex实现应用程序单例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DemoCSDN
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            bool createNew;
            using (System.Threading.Mutex mutex = new System.Threading.Mutex(true, Application.ProductName, out createNew))
            {
                try
                {
                    if (createNew)
                    {
                        try
                        {
                            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
                            Application.EnableVisualStyles();
                            Application.SetCompatibleTextRenderingDefault(false);
                            Application.Run(new Form1());
                        }
                        //注册捕捉异常事件
                        catch (Exception ex)
                        {
                            //MessageBox.Show(ex.Message);
                            //TraceLog.Write(ex.Message);
                        }
                    }
                    else
                    {
                        MessageBox.Show("The progam is running ...");
                        System.Environment.Exit(1);
                    }

                }
                finally
                {
                    //只有第一个实例获得控制权,因此只有在这种情况下才需要ReleaseMutex,否则会引发异常。
                    if (createNew)
                    {
                        mutex.ReleaseMutex();
                    }
                    mutex.Close();
                }
            }
        }
        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            Exception ex = e.Exception;
            MessageBox.Show(ex.Message);
            //做一些极其简单的记录异常信息操作
        }
    }
}

Mutex有个最常见的用途:上述用于控制一个应用程序只能有一个实例运行。

要实现应用程序的单例,需要在在整个应用程序运行过程中都保持Mutex,而不只是在程序初始阶段。所以,例子中Mutex的建立和销毁代码包裹了整个Main()函数。

猜你喜欢

转载自blog.csdn.net/zhuxipan1990/article/details/82979077