1

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

1

4 Answers 4

12

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();
}
Sign up to request clarification or add additional context in comments.

3 Comments

Here is a link, perhaps tekBlues could update the answer with the code sample. programmersheaven.com/mb/csharp/209938/209938/… NOTE: I haven't tested this sample.
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
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
1

try System.Diagnostics.Process

getProcesses()

Comments

1

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

1 Comment

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

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.