简体   繁体   English

怎么做:应用程序的第一个实例将执行一个进程,第二个实例将在以后终止该进程

[英]How to do: The first instance of an app will execute a process, second instance will kill the process later

I want to create a console application that behaves as follows: 我想创建一个行为如下的控制台应用程序:

  1. The first instance of the app will execute a process. 应用程序的第一个实例将执行一个进程。
  2. The second instance executed later will kill the process. 稍后执行的第二个实例将终止该进程。

Is there a simple way to do so? 有一个简单的方法吗?

EDIT: The second instance also terminates the first instance and itself. 编辑:第二个实例也终止第一个实例和它自己。

EDIT 2: 编辑2:

More details scenario is as follows: 更多细节场景如下:

Assume there is no instance of my application running. 假设没有运行我的应用程序的实例。 If I execute my application, the new instance will run. 如果我执行我的应用程序,新实例将运行。 The application will create a process that execute Adobe Acrobat Reader X (for example). 该应用程序将创建一个执行Adobe Acrobat Reader X的过程(例如)。

Later, I execute my application again just to kill the running Adobe Acrobat Reader X and of course its host (the first instance of my application). 之后,我再次执行我的应用程序只是为了杀死正在运行的Adobe Acrobat Reader X,当然还有它的主机(我的应用程序的第一个实例)。

You need to implement a mutex to do this. 您需要实现互斥锁才能执行此操作。

     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;
        }
      }

You can create a process with a known name. 您可以使用已知名称创建进程。 Then when the application starts you could get a list with all the processes that are running. 然后,当应用程序启动时,您可以获得包含正在运行的所有进程的列表。 If the process is not there you can start it, if it's already there you can kill the process and exit. 如果进程不在那里你可以启动它,如果它已经存在,你可以终止进程并退出。

A more elegant solution would be as Max suggested to use a Mutex to communicate between the processes. 更优雅的解决方案是Max建议使用Mutex在进程之间进行通信。 For example to be sure that you don't kill another process with the same name. 例如,确保不要使用相同名称杀死另一个进程。

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

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