How can I check for multiple instances of my visual basic application? When the user runs the application, I want to know how many instances are already open. Thank you.
+1
A:
The "fastest" way would be use to the System.Diagnostics.Process class to find all instances of your specific process name if all you want to do is get the count of processes.
So, as an example to find instances of "Explorer" use this.
Dim instanceCount As Integer = Process.GetProcessesByName("explorer").Count()
Console.WriteLine(String.Format("{0} Instances Running", instanceCount.ToString()))
Console.ReadLine()
If you are looking to limit users to 1 instance, then I would look at creating a named Mutex and using that to prevent others from starting.
Mitchel Sellers
2010-08-30 17:35:16
The Visual Basic project properties "Application" tab has a checkbox for "Make single instance application" that deals with the mutexness for you.
Will A
2010-08-30 17:44:12
The corollary of this answer is to make sure you don't name your program "Explorer".
Hans Passant
2010-08-30 17:54:43
Good point Hans!
Mitchel Sellers
2010-08-30 18:11:22
This is exactly what I needed. Thank you.
Louise
2010-08-30 18:15:45
+2
A:
Share a semaphore between the processes, and add a permit for every upstart. The most staight-forward way is probably to use a named semaphore. See the remarks section on http://msdn.microsoft.com/en-us/library/ms682438%28VS.85%29.aspx for details.
disown
2010-08-30 17:37:59
Why? A semaphore is one of the most basic building blocks of concurrent apps, I wouldn't call it complicated.
disown
2010-08-30 17:43:56
One complication: There doesn't seem to be a good way of getting the current count without releasing, so you will need to do a release / waitforsingleobject to get the count.
disown
2010-08-30 17:48:17