繁体   English   中英

如何计划流程。在WPF中开始

[英]How to Schedule a Process.Start in WPF

我正在尝试重新启动WPF中的应用程序。

我尝试了以下方法:

Process.Start(Application.ExecutablePath);
Process.GetCurrentProcess().Kill();

而且它不起作用,因为该应用程序被设置为单个实例应用程序。

然后我就累了:

Process.GetCurrentProcess().Kill();
Process.Start(Application.ExecutablePath);

而且它不起作用,因为一旦我们终止进程,它就不会到达第2行

有没有一种方法可以安排.Start,这样我就不会遇到问题#1。

您可以启动辅助应用程序,然后在延迟后重新启动您的主程序。 几年前,当我编写一个自我更新程序时,这就是我所采用的实现路径。 这只是一个简单的程序,将可执行文件作为命令行参数arg,会休眠十分之一秒,然后启动。

比我采用的更好的实现途径是让新启动的程序等待启动它的进程终止。 等待任意时间长度可能会使事情复杂化。 为了完成此任务,我可能会将进程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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM