Can the Process Class be used to determine if a process is already running?
I'm using the Process Class to start processes, but don't ever want more than one instance of any program to be running.
Looking at the documentation, there are lots of likely-looking properties, but nothing that stands out as the most obvious.
What's the best way 开发者_如何学Cto determine if a process is running?
Edit: John Fisher is right: it's an existing application that I'm starting and I'm unable to modify it.
You can call this method
Process.GetProcesses()
and loop through the result (a collection of type Process) to see if the name matches. Something like this:
foreach (Process prc in Process.GetProcesses())
{
if (prc.ProcessName.Contains(MyProcessName))
{
//Process is running
}
}
I guess that all depends on what you mean by "best way"? Do you mean the fastest, the most accurate, or one that will handle some odd circumstances?
The way I would start is by listing the processes and checking the executable file name against the one I'm trying to start. If they match (case insensitive), it's probably running.
You should use the Singleton application pattern for that:
bool createdNew = true;
using (var mutex = new Mutex(true, "YourProcessName", out createdNew))
{
if (createdNew)
{
// Run application
}
}
精彩评论