views:

317

answers:

4

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

+11  A: 

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();
}
tekBlues
Here is a link, perhaps tekBlues could update the answer with the code sample. http://www.programmersheaven.com/mb/csharp/209938/209938/how-can-i-check-if-my-application-is-already-running/?S=B20000 NOTE: I haven't tested this sample.
Nathan Koop
A mutex is a better option than inspecting the processes because you may not have permissions to look through the processes but you dont have to worry about that w/ a mutex
Allen
If you're going to do this, you have to make 100% sure that your app can't lock up, or else you'll end up DOS'ing yourself
Paul Betts
A: 

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.

Andrew Weir
+1  A: 

try System.Diagnostics.Process

getProcesses()

SP
+1  A: 

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

Jamie Ide
Thanks, that was very simple! (which is all I can handle at this point)