C# FrameworkAPI之Mutex實現應用程式單例
阿新 • • 發佈:2018-11-10
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()函式。