如何计划在WPF中的Process.Start
-
27-09-2019 - |
题
我试图重新启动在WPF应用程序。
我试过如下:
Process.Start(Application.ExecutablePath);
Process.GetCurrentProcess().Kill();
和它不工作,因为应用程序是设置为单个应用程序实例
然后我累这样:
Process.GetCurrentProcess().Kill();
Process.Start(Application.ExecutablePath);
和它不工作,因为一旦我们杀它不会碰到生产线2
有没有一种方法来安排的。开始,这样我就不会遇到问题#1。
解决方案
您可以启动辅助应用程序的延迟之后会再重新启动您的主程序。当我写了一个自我更新,几年前,这是实施路径,我拿了。这只是一个简单的程序,把所述可执行作为命令行参数,将睡十分之一秒,那么它。开始
比我花了将有新推出的项目等待启动它终止进程,更好的实现路径。等待的时间可能使问题复杂化的任意长度。为了做到这一点,我可能会进程ID传递到重新启动,这样它会确切地知道要等上哪个进程。
其他提示
这并不难,因为你的想法。所有你需要做的是调用以下方法,在命令行通过为重新启动的实例:
public static void RestartMe(string commandLine)
{
var myId = Process.GetCurrentProcess().Id;
var myPath = Assembly.GetEntryAssembly().CodeBase.Replace("file:///", "");
var systemPath = typeof(object).Assembly.CodeBase.Replace("file:///", "");
var tempPath = Path.GetTempFileName();
File.WriteAllText(tempPath + ".cs", @"
using System;
using System.Diagnostics;
public class App
{
public static void Main(string[] args)
{
try { Process.GetProcessById(" + myId + @").WaitForExit(); } catch {}
Process.Start(""" + myPath + @""", Environment.CommandLine);
}
}");
var compiler = new ProcessStartInfo
{
FileName = Path.Combine(Path.GetDirectoryName(systemPath), "csc.exe"),
Arguments = tempPath + ".cs",
WorkingDirectory = Path.GetDirectoryName(tempPath),
WindowStyle = ProcessWindowStyle.Hidden,
};
var restarter = new ProcessStartInfo
{
FileName = tempPath + ".exe",
Arguments = commandLine,
WindowStyle = ProcessWindowStyle.Hidden,
};
Process.Start(compiler).WaitForExit();
Process.Start(restarter); // No WaitForExit: restarter WaitForExits us instead
File.Delete(tempPath);
File.Delete(tempPath + ".cs");
Environment.Exit(0);
}
它是如何工作的:这实际上并创造另一个“重新启动装置”的计划,但确实它怕疼和自动。在重启程序有当前的进程ID,并内置到它的可执行文件名。它总能找到编译器,因为.NET Framework版本附带在同一文件夹中System.dll中兼容CSC.EXE。
不隶属于 StackOverflow