Reputation: 6756
I have program of which i have to launch multiple instances.
However i have to perform some actions if the present instance is the last instance.
Is there any way to do so ? If yes then how do i do it ?
Upvotes: 1
Views: 152
Reputation: 28355
You should note that all other answerers don't order application instances.
How do you want to order your applications? By the start time? If so, you can use Isolated storage for your code, storing there a date of last start of your application instance, and compare it with start date for this current instance (make a static property in your application). See too: MSDN article.
If you don't want to order your applications, just use the Process.GetProcessesByName, simply passing there a name for your application.
Note that debug mode process name differs from release mode process name
Upvotes: 0
Reputation: 31241
if(Process.GetProcessesByName("yourprogram").Length == 0)
{
// It's the only instance!
}
Upvotes: 2
Reputation: 1262
In CLR via C# book by Jeffrey Richter it was an example to use Semaphore
class for this:
using System;
using System.Threading;
public static class Program {
public static void Main() {
bool created;
using(new Semaphore(0, 1, "SomeUniqueStringIdentifyingMyApp", out created)) {
if(created) {
//This thread created kernel object so no other instance of this app must be running
} else {
//This thread opens existing kernel object with the same string name which means
//that another instance of this app must be running.
}
}
}
}
Upvotes: 0
Reputation: 7105
The best way is probably to count the number of running processes
var count = System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count();
Upvotes: 2
Reputation: 12904
You could get a list of the processes with the same name as the current and act accordingly;
System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("Name.of.process.here");
if(processes.Length == 1)
Upvotes: 2