2010-08-04 31 views
4

我有一個自定義的ApplicationContext,如果滿足特定的條件,我試圖終止它。我正在使用Mutex來確保單個實例。我試過base.OnMainFormClosed(null, null);Application.Exit()ExitThread。一切都停止處理,但流程本身仍在運行。從ApplicationContext退出應用程序

完全Main()方法:

static void Main() 
    { 
     bool firstInstance; 
     using (Mutex mutex = new Mutex(true, 
            @"Global\MyApplication", 
            out firstInstance)) 
     { 
      if (!firstInstance) 
      { 
       MessageBox.Show("Another instance is already running."); 
       return; 
      } 

      Application.EnableVisualStyles(); 
      Application.SetCompatibleTextRenderingDefault(false); 

      Application.Run(new CustomContext()); 
     } 
    } 

什麼是正確的方法?

+0

在'Main'方法什麼的線程只是打電話? – SLaks 2010-08-04 09:06:57

+0

'Application.Run(new CustomContext());' – mattdwen 2010-08-04 09:14:40

+0

您是否在代碼中使用任何構造函數或某些東西。 – Dotnet 2010-08-04 09:16:04

回答

6
Application.Run(new CustomContext()); 

這沒關係,但你不存儲你所創建的CustomContext對象的引用。因此沒有辦法調用它的ExitThread方法。像這樣調整:

class Program { 
    private static CustomContext appContext; 

    [STAThread] 
    public static void Main() { 
     // Init code 
     //... 
     appContext = new CustomContext(); 
     Application.Run(appContext); 
    } 
    public static void Quit() { 
     appContext.ExitThread(); 
    } 
} 

現在您可以簡單地調用Program.Quit()來停止消息循環。

檢查我的答案this thread以獲得更好的實現單實例應用程序的方法。 WindowsFormsApplicationBase類還提供ShutdownStyle屬性,可能對您有用,而不是ApplicationContext。

+0

我在其他線程中使用過你的例子。 – mattdwen 2010-08-10 01:23:42

+0

應該是「public static void Quit」;) – juFo 2013-01-25 13:10:05

0

調用Application.Exit會停止程序的消息循環。
這會導致主要的Application.Run調用(通常在Main())終止。

調用Applcication.Exit()之後,執行Application.Run()調用後Main()中的任何代碼。

Application.Run通常是Main()中的最後一行,因此調用Applcication.Exit()通常會導致進程停止。

您可能在Application.Run()之後有更多的代碼,或者處於某處的死鎖。


在調試器中暫停進程並檢查它在做什麼。

+0

調試器暫停在Application.Run行。調用堆棧在上面和下面顯示'[External Code]'。 我也使用互斥來確保一個實例,我可能應該在開始時指出這個實例。我會用完整的方法更新問題。 – mattdwen 2010-08-04 09:22:11

+0

@mattdwen:你是否在Debugger選項中禁用了我的代碼? – SLaks 2010-08-04 10:05:47

-1

您可以在您要退出

Thread.CurrentThread.Abort();