WPFでProcess.Startをスケジュールする方法
-
27-09-2019 - |
質問
WPFでアプリケーションを再開しようとしています。
以下を試しました:
Process.Start(Application.ExecutablePath);
Process.GetCurrentProcess().Kill();
また、アプリケーションが単一のインスタンスアプリケーションとして設定されているため、機能しません。
それから私はこれを疲れました:
Process.GetCurrentProcess().Kill();
Process.Start(Application.ExecutablePath);
プロセスを殺すと、2行目にヒットしないので機能しません
Issue#1に遭遇しないように、.STARTをスケジュールする方法はありますか。
解決
遅延後にメインプログラムを再起動する二次アプリケーションを起動できます。数年前にセルフアップデーターを書いたとき、それが私がとった実装パスでした。それは、実行可能ファイルをコマンドラインのArgとして使用した単純なプログラムであり、10分の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);
}
それがどのように機能するか:これにより、実際に別の「Restarter」プログラムが作成されますが、痛みなく自動的に行います。 Restarterプログラムには、現在のプロセスIDと実行可能ファイル名があります。 Net Frameworkバージョンは、System.dllと同じフォルダーに互換性のあるCSC.exeが出荷されるため、常にコンパイラが見つかります。
所属していません StackOverflow