C#實現單例項執行

滄海一滴發表於2013-09-16

C#實現單例項執行的方法,也有多種,比如利用 Process 查詢程式的方式,利用 API findwindow 查詢窗體的方式,還有就是 利用 Mutex 原子操作,上面幾種方法中, 綜合考慮利用 Mutex 的方式是較好的選擇。

[STAThread]
static void Main()
{
    bool isAppRunning = false;
    System.Threading.Mutex mutex = new System.Threading.Mutex(
        true,
        System.Diagnostics.Process.GetCurrentProcess().ProcessName,
        out isAppRunning);
    if (!isAppRunning)
    {
        MessageBox.Show("本程式已經在執行了,請不要重複執行!");
        Environment.Exit(1);
    }
    else
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}
 
使用Process 查詢程式的方式會報錯:System.ComponentModel.Win32Exception 中第一次偶然出現的“System.dll”型別的異常
原因可能是因為:
有些程式,如:system 系統空閒程式,當前程式沒有許可權獲取相關資訊或有些程式沒有process.MainModule.FileName這些屬性
示例程式碼:

           bool result = false;
            try
            {
                Process me = Process.GetCurrentProcess();
                Process[] us = Process.GetProcesses();
                Process another = null;
                foreach (var p in us)
                {
                    try
                    {
                        if (p.Id != me.Id && p.MainModule.FileName == me.MainModule.FileName)
                        {
                            another = p;
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex);
                    }
                }
                if (another != null)
                {
                    MessageBox.Show("程式已執行", "系統提示", MessageBoxButtons.OK, MessageBoxIcon.Question);
                    result = true;
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.StackTrace+“\n”+ e.Message);
                result = true;
            }
            return result;
 
 
 
 
http://xxinside.blogbus.com/logs/47162540.html

相關文章