Peter
Peter

Reputation:

How to detect if my program is running in Windows?

I am writing a C# console app. It's going to run as a scheduled task.

I want my EXE to exit quickly if it finds that another process is still running from the previous schedule task execution.

I can't seem to find the way to let my app detect the active processes, and so know whether it's already running or not.

Thanks for any ideas. Peter

Upvotes: 1

Views: 1374

Answers (4)

Jamie Ide
Jamie Ide

Reputation: 49251

Use a mutex:

// Allow only one instance of app
// See http://www.yoda.arachsys.com/csharp/faq/#one.application.instance
bool firstInstance;
_mutex = new Mutex(false, "Local\\[UniqueName]", out firstInstance);

Link to reference in comment

Upvotes: 1

tekBlues
tekBlues

Reputation: 5793

One very common technique is to create a mutex when your process starts. If you cannot create the mutex it means there is another instance running.

This is the sample from 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();
}

Upvotes: 12

Erix
Erix

Reputation: 7105

try System.Diagnostics.Process

getProcesses()

Upvotes: 1

Andrew Weir
Andrew Weir

Reputation: 1030

Isn't there something in System.Diagnostics for checking processes?

Edit: Do any of these links help you? I can see how they might be useful.

I'm sorry that all I can do is provide you links to other items. I've never had to use System.Diagnostics but hopefully it might help you or someone else out.

Upvotes: 0

Related Questions