2014-10-08 67 views
-2

內部的Program.cs我所做的:我正在檢查我的應用程序是否已經運行,並且它說運行,即使我停止應用程序爲什麼?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Windows.Forms; 
using System.Diagnostics; 
using DannyGeneral; 

namespace mws 
{ 
    static class Program 
    { 
     /// <summary> 
     /// The main entry point for the application. 
     /// </summary> 
     [STAThread] 
     static void Main() 
     { 
      try 
      { 
       if (IsApplicationAlreadyRunning() == true) 
       { 
        MessageBox.Show("The application is already running"); 
       } 
       else 
       { 
        Application.EnableVisualStyles(); 
        Application.SetCompatibleTextRenderingDefault(false); 
        Application.Run(new Form1()); 
       } 
      } 
      catch (Exception err) 
      { 
       Logger.Write("error " + err.ToString()); 
      } 
     } 
     static bool IsApplicationAlreadyRunning() 
     { 
      string proc = Process.GetCurrentProcess().ProcessName; 
      Process[] processes = Process.GetProcessesByName(proc); 
      if (processes.Length > 1) 
      { 
       return true; 
      } 
      else 
      { 
       return false; 
      } 
     } 
    } 
} 

我用了一個斷點,即使我閉上了計劃在此從Visual Studio和我嘗試再次運行該應用程序它返回true,並拋出消息應用程序已經是runnig了。

在斷點我看到變量PROC包含:我的天氣Station.vshost

,現在我注意到了這一點只有當我在一個新的Visual Studio窗口中打開我的應用程序的另一個副本和應用上發生另一個硬盤上的另一個位置,我沒有在任何視覺工作室窗口上運行應用程序。

那麼,爲什麼當我有相同的應用程序在Visual Studio中打開兩次,它沒有運行它認爲它正在運行? 即使我關閉第二個視覺工作室,我仍然在proc My Weather Station.vshost中看到,但是這次它返回false。

編輯

我現在該變量的過程中指數在0和1我的天氣Station.vshost 包含兩次,如果我關閉第二視覺工作室它僅包含一個看到的。

問題是這是什麼我的天氣Station.vshost?如果應用程序未運行,爲什麼它將其視爲正在運行的應用程序?我如何使這個檢查更好,所以如果我打開我的應用程序的更多副本,它不會認爲該應用程序正在運行?

我想打開我的應用程序的另一個副本的原因是,第二個更舊,我想看看我做的一些舊事情。

我可以改變這一點:

if (processes.Length > 1) 

,並使其> 10例如 但我仍然不明白什麼是我的天氣Station.vshost?爲什麼它在內存中運行?爲什麼它將其視爲正在運行的應用程序?

+0

如果您試圖確保只有一個實例正在運行,請嘗試此線程'http://stackoverflow.com/questions/184084/how-to-force-c-sharp-net-app-to-只運行一個實例在窗口中 – KSdev 2014-10-08 19:33:39

+0

[防止應用程序啓動如果已經運行]的可能的重複(http://stackoverflow.com/questions/18477502/prevent-application-launch-if-already-running) – 2014-10-08 19:35:20

+0

[用戶嘗試打開新實例時返回已打開的應用程序]可能的重複(http://stackoverflow.com/questions/94274/return-to-an-already-open-application-when-a-user -try-to-open-a-new-instance) – 2014-10-08 19:44:11

回答

相關問題