gpt4 book ai didi

c# - : The first instance of an app will execute a process, second instance will kill the process later 怎么办

转载 作者:太空宇宙 更新时间:2023-11-03 22:18:09 26 4
gpt4 key购买 nike

我想创建一个行为如下的控制台应用程序:

  1. 应用程序的第一个实例将执行一个流程。
  2. 稍后执行的第二个实例将终止进程。

有没有简单的方法可以做到这一点?

编辑:第二个实例也终止第一个实例和它自己。

编辑 2:

更多细节场景如下:

假设我的应用程序没有运行实例。如果我执行我的应用程序,新实例将运行。该应用程序将创建一个进程来执行 Adob​​e Acrobat Reader X(例如)。

稍后,我再次执行我的应用程序只是为了终止正在运行的 Adob​​e Acrobat Reader X,当然还有它的主机(我的应用程序的第一个实例)。

最佳答案

你需要实现一个互斥锁来做到这一点。

     private static Mutex mutex = null;

private void CheckIfRunning() {

string strId = "291B62B2-812A-4a13-A657-BA672DD0C93B";

bool bCreated;

try
{
mutex = new Mutex(false, strId, out bCreated);
}
catch (Exception)
{
bCreated = false;
//Todo: Kill your process
}

if (!bCreated)
{
MessageBox.Show(Resources.lbliLinkAlreadyOpen, Resources.lblError, MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
}

关于c# - : The first instance of an app will execute a process, second instance will kill the process later 怎么办,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4257524/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com