2010-01-15 19 views

回答

9

Application.Restart()是你的方法:)

Here是另一個StackOverflow的答案是指出了幾個「手錶出了的」的使用這種方法。

0

我也有類似的問題,但我是關係到不可收拾的內存泄漏,我不能對具有全天候運行的應用程序找到。對於客戶,我同意如果內存消耗超過定義的值,則重新啓動應用程序的安全時間爲上午03:00。

我試過Application.Restart,但因爲它似乎使用一些啓動,而它已經在運行新實例的機制,我去了另一個方案。我使用了文件系統句柄持續存在的技巧,直到創建它們的進程死亡。所以,從應用程序,我把文件放到磁盤上,並沒有Dispose()的句柄。我使用該文件發送「我自己」的可執行文件和啓動目錄(以增加靈活性)。

代碼:

_restartInProgress = true; 
string dropFilename = Path.Combine(Application.StartupPath, "restart.dat"); 
StreamWriter sw = new StreamWriter(new FileStream(dropFilename, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite)); 
sw.WriteLine(Application.ExecutablePath); 
sw.WriteLine(Application.StartupPath); 
sw.Flush(); 
Process.Start(new ProcessStartInfo 
{ 
    FileName = Path.Combine(Application.StartupPath, "VideoPhill.Restarter.exe"), 
    WorkingDirectory = Application.StartupPath, 
    Arguments = string.Format("\"{0}\"", dropFilename) 
}); 
Close(); 

Close()在年底將啓動的應用程序停機,並且文件句柄我用StreamWriter這裏將舉行開到過程真的死了。然後......

Restarter.exe進入行動。它嘗試以獨佔模式讀取文件,阻止它獲得訪問權限,直到主應用程序未死,然後啓動主應用程序,刪除文件並存在。我猜想,這不能簡單:

static void Main(string[] args) 
{ 
    string filename = args[0]; 
    DateTime start = DateTime.Now; 
    bool done = false; 
    while ((DateTime.Now - start).TotalSeconds < 30 && !done) 
    { 
     try 
     { 
      StreamReader sr = new StreamReader(new FileStream(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)); 
      string[] runData = new string[2]; 
      runData[0] = sr.ReadLine(); 
      runData[1] = sr.ReadLine(); 
      Thread.Sleep(1000); 
      Process.Start(new ProcessStartInfo { FileName = runData[0], WorkingDirectory = runData[1] }); 
      sr.Dispose(); 
      File.Delete(filename); 
      done = true; 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine(ex.Message); 
     } 
     Thread.Sleep(1000); 
    } 
}