我有一个类似的问题,但我的是无法管理的内存泄漏,我无法找到一个必须全天候运行的应用程序。对于客户,我同意如果内存消耗超过定义的值,则重新启动应用程序的安全时间为上午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