如何检查并终止我的应用程序的另一个实例?

tha*_*usu 4 c# kill-process windows-runtime windows-store-apps

我面临的问题是我的客户已经在运行应用程序 appA。然后他们转到桌面(而不是杀死 appA),并通过使用 PowerShell 运行 appA.ps1 来升级应用程序的版本。之后,安装后点击 appA -> get an exception。我想根本原因是有另一个实例正在运行。

我的问题是如何检查我的应用程序是否已经在运行?我可以杀死它吗?

另外,我的应用程序是 windows 8 商店,c#。

小智 6

如果您想保持当前实例运行并终止应用程序的所有其他实例,您可以这样做:

 using namespace System.Diagnostics;

 ...

 // get current process
 Process current = Process.GetCurrentProcess();
 // get all the processes with currnent process name
 Process[] processes = Process.GetProcessesByName(current.ProcessName);
 
 foreach (Process process in processes)
 {
     //Ignore the current process  
     if (process.Id != current.Id)
     {
        process.Kill();
     }
 }
Run Code Online (Sandbox Code Playgroud)


And*_*ndy 0

来自社交 MSDN

所有Metro风格的应用程序都工作在高度沙盒的环境中,无法直接启动外部应用程序。

您无法访问 Windows 应用程序进程。不幸的是,您无法检查正在运行的 Windows 应用程序。

到目前为止我还没有找到其他方法。


没有 Metro 风格的应用程序

首先,您需要以下流程:

var processes = Process.GetProcessesByName("your application name")
Run Code Online (Sandbox Code Playgroud)

检查你的程序是否已经在运行:

var isRunning = processes.Length > 1;
Run Code Online (Sandbox Code Playgroud)

然后循环它们并关闭进程:

foreach (var process in processes)
{
    process.CloseMainWindow();

    // OR more aggressive:
    process.Kill();
}
Run Code Online (Sandbox Code Playgroud)