我有一個類似的問題,但我的是無法管理的內存泄漏,我無法找到一個必須全天候運行的應用程序。對於客戶,我同意如果內存消耗超過定義的值,則重新啓動應用程序的安全時間爲上午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);
}
}
請注意,如果您的用戶重命名該exe文件,他們仍然可以啓動多個副本。 – SLaks 2009-10-30 03:20:38