如何检测我的程序是否在Windows中运行?

1 c# windows console

我正在编写一个C#控制台应用程序.它将作为计划任务运行.

如果发现另一个进程仍在从先前的计划任务执行中运行,我希望我的EXE快速退出.

我似乎找不到让我的应用程序检测活动进程的方法,因此知道它是否已经运行.

谢谢你的任何想法.彼得

tek*_*ues 12

一种非常常见的技术是在进程启动时创建互斥锁.如果您无法创建互斥锁,则表示正在运行另一个实例.

这是来自Nathan's Link的样本:

//Declare a static Mutex in the main form or class...
private static Mutex _AppMutex = new Mutex(false, "MYAPP");

// Check the mutex before starting up another possible instance
[STAThread]
static void Main(string[] args) 
{
  if (MyForm._AppMutex.WaitOne(0, false))
  {
    Application.Run(new MyForm());
  }
  else
  {
    MessageBox.Show("Application Already Running");
  }
  Application.Exit();
}
Run Code Online (Sandbox Code Playgroud)