Reputation:
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
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);
Upvotes: 1
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
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