Results 1 to 12 of 12

Thread: [1.0/1.1] Use mutex to find the multiple instance

  1. #1

    Thread Starter
    PowerPoster eranga262154's Avatar
    Join Date
    Jun 2006
    Posts
    2,201

    Question [1.0/1.1] Use mutex to find the multiple instance


    Hi all,

    I have write a service to automate a server application. To start the application I need some IPs which are stored in a database. I read the database and get required IPs on my service and run the server.

    Up to now everything is ok.

    Now I want to check that there is multiple instance are available. Because I can start only one server at a time. To do this I try to use MUTEX, as in C++(my server is written on C++). Can you guys give me a help. I don't know that higher concepts to handle in C#.

    Thanks a lot.
    “victory breeds hatred, the defeated live in pain; happily the peaceful live giving up victory and defeat” - Gautama Buddha

  2. #2
    Fanatic Member daimous's Avatar
    Join Date
    Aug 2005
    Posts
    657

    Re: [1.0/1.1] Use mutex to find the multiple instance

    try this...
    Code:
           [STAThread]
            static void Main()
            {
                string MutexName = "MutexNameHere";
                bool grantedOwnership;
                System.Threading.Mutex singleIntanceMutex = new System.Threading.Mutex(true, MutexName, out grantedOwnership);
                try
                {
                    if (grantedOwnership)
                    {
                        Application.EnableVisualStyles();
                        Application.SetCompatibleTextRenderingDefault(false);
                        Application.Run(new frmIndex());
                    }
                    else
                    {
                        MessageBox.Show("Another Instance of this application is already running.", "BCMD", MessageBoxButtons.OK, MessageBoxIcon.Information);
    
                    }
                }
                finally
                {
                    singleIntanceMutex.Close();
                }
    
    
            }

  3. #3
    Interweb adm/o/distrator Paul M's Avatar
    Join Date
    Nov 2006
    Location
    Australia, Melbourne
    Posts
    2,306

    Re: [1.0/1.1] Use mutex to find the multiple instance

    Heres another way

    Code:
    static void Main()
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                
                int count = CheckForRunningInstances();
    
                if (count <= 1)
                {
                    Application.Run(new Form1());
                }
                else
                {
                    System.Windows.Forms.MessageBox.Show("Another instance of this program is already running.  Two instances cannot run at the same time", "Already running", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    Application.Exit();
                }
    
            }
            private static int CheckForRunningInstances()
            {
    
                string[] parts = System.Reflection.Assembly.GetExecutingAssembly().Location.Split("\\".ToCharArray());
                string appName = parts[parts.Length - 1];
    
                string query = "select name from CIM_Process where name = '" + appName + "'";
    
                System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher(query);
    
                int hInstCount = 0;
    
                foreach (System.Management.ManagementObject item in searcher.Get())
                {
                    hInstCount++;
                    if (hInstCount > 1) break;
                }
                return hInstCount;
            }

  4. #4
    KrisSiegel.com Kasracer's Avatar
    Join Date
    Jul 2003
    Location
    USA, Maryland
    Posts
    4,985

    Re: [1.0/1.1] Use mutex to find the multiple instance

    My codebank submission submitted in early 2006: http://www.vbforums.com/showthread.php?t=397006


    Quote Originally Posted by Paul M
    Heres another way
    That's horribly inefficient especially compared to the simplicity of using a mutex.
    KrisSiegel.com - My Personal Website with my blog and portfolio
    Don't Forget to Rate Posts!

    Free Icons: FamFamFam, VBCorner, VBAccelerator
    Useful Links: System.Security.SecureString Managed DPAPI Overview Part 1 Managed DPAPI Overview Part 2 MSDN, MSDN2, Comparing the Timer Classes

  5. #5
    Interweb adm/o/distrator Paul M's Avatar
    Join Date
    Nov 2006
    Location
    Australia, Melbourne
    Posts
    2,306

    Re: [1.0/1.1] Use mutex to find the multiple instance

    mutex is just easier to use, this one gives you a lot more options

  6. #6
    KrisSiegel.com Kasracer's Avatar
    Join Date
    Jul 2003
    Location
    USA, Maryland
    Posts
    4,985

    Re: [1.0/1.1] Use mutex to find the multiple instance

    Quote Originally Posted by Paul M
    mutex is just easier to use, this one gives you a lot more options
    I fail to see how it gives you more options. You're just iterating through assemblies and using more memory and cpu than necessary. If you can come up with any advantages I'd love to hear them though. I love learning new techniques.

    As for mutex; a mutex is the propery way to accomplish single instances. Most single instance C++ applications also use this technique.
    KrisSiegel.com - My Personal Website with my blog and portfolio
    Don't Forget to Rate Posts!

    Free Icons: FamFamFam, VBCorner, VBAccelerator
    Useful Links: System.Security.SecureString Managed DPAPI Overview Part 1 Managed DPAPI Overview Part 2 MSDN, MSDN2, Comparing the Timer Classes

  7. #7
    Interweb adm/o/distrator Paul M's Avatar
    Join Date
    Nov 2006
    Location
    Australia, Melbourne
    Posts
    2,306

    Re: [1.0/1.1] Use mutex to find the multiple instance

    Code:
            private static int GetNumberOfRunningInstances()
            {
                int runcount = 0;
    
                string[] parts = System.Reflection.Assembly.GetExecutingAssembly().Location.Split("\\".ToCharArray());
                string appName = parts[parts.Length - 1];
    
                string query = "select name from CIM_Process where name = '" + appName + "'";
    
                System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher(query);
    
                foreach (System.Management.ManagementObject item in searcher.Get())
                {
                    runcount++;
                }
                return runcount;
            }
    That was my original code for a project i had to make that had to check the number of running instances. But the assembly class also allows the developer to further explore the assembly if required. I only edited and posted the code for fun and just to show another way. But for something as simple as to only allow one instance mutex would best serve the developer as it is basically its primary job.

  8. #8
    KrisSiegel.com Kasracer's Avatar
    Join Date
    Jul 2003
    Location
    USA, Maryland
    Posts
    4,985

    Re: [1.0/1.1] Use mutex to find the multiple instance

    The assembly you're looking for should be your own... so why would you need to explore it further?
    KrisSiegel.com - My Personal Website with my blog and portfolio
    Don't Forget to Rate Posts!

    Free Icons: FamFamFam, VBCorner, VBAccelerator
    Useful Links: System.Security.SecureString Managed DPAPI Overview Part 1 Managed DPAPI Overview Part 2 MSDN, MSDN2, Comparing the Timer Classes

  9. #9
    Frenzied Member axion_sa's Avatar
    Join Date
    Jan 2002
    Location
    Joburg, RSA
    Posts
    1,724

    Re: [1.0/1.1] Use mutex to find the multiple instance

    Quote Originally Posted by Paul M
    Code:
            private static int GetNumberOfRunningInstances()
            {
                int runcount = 0;
    
                string[] parts = System.Reflection.Assembly.GetExecutingAssembly().Location.Split("\\".ToCharArray());
                string appName = parts[parts.Length - 1];
    
                string query = "select name from CIM_Process where name = '" + appName + "'";
    
                System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher(query);
    
                foreach (System.Management.ManagementObject item in searcher.Get())
                {
                    runcount++;
                }
                return runcount;
            }
    That was my original code for a project i had to make that had to check the number of running instances. But the assembly class also allows the developer to further explore the assembly if required. I only edited and posted the code for fun and just to show another way. But for something as simple as to only allow one instance mutex would best serve the developer as it is basically its primary job.
    Won't work if your application is hosted in a secondary AppDomain

  10. #10

    Thread Starter
    PowerPoster eranga262154's Avatar
    Join Date
    Jun 2006
    Posts
    2,201

    Re: [1.0/1.1] Use mutex to find the multiple instance

    Thanks pal for your code. But I'm confusing with that Forms and Service I have work on. I'll check it and back, if I stuck.
    “victory breeds hatred, the defeated live in pain; happily the peaceful live giving up victory and defeat” - Gautama Buddha

  11. #11

    Thread Starter
    PowerPoster eranga262154's Avatar
    Join Date
    Jun 2006
    Posts
    2,201

    Re: [1.0/1.1] Use mutex to find the multiple instance

    Quote Originally Posted by Paul M
    Heres another way

    Code:
    static void Main()
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                
                int count = CheckForRunningInstances();
    
                if (count <= 1)
                {
                    Application.Run(new Form1());
                }
                else
                {
                    System.Windows.Forms.MessageBox.Show("Another instance of this program is already running.  Two instances cannot run at the same time", "Already running", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    Application.Exit();
                }
    
            }
            private static int CheckForRunningInstances()
            {
    
                string[] parts = System.Reflection.Assembly.GetExecutingAssembly().Location.Split("\\".ToCharArray());
                string appName = parts[parts.Length - 1];
    
                string query = "select name from CIM_Process where name = '" + appName + "'";
    
                System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher(query);
    
                int hInstCount = 0;
    
                foreach (System.Management.ManagementObject item in searcher.Get())
                {
                    hInstCount++;
                    if (hInstCount > 1) break;
                }
                return hInstCount;
            }

    Thanks, but I got an error on "Application" that namespace is not found. I couldn't find the definition either. What should I do.
    “victory breeds hatred, the defeated live in pain; happily the peaceful live giving up victory and defeat” - Gautama Buddha

  12. #12

    Thread Starter
    PowerPoster eranga262154's Avatar
    Join Date
    Jun 2006
    Posts
    2,201

    Re: [1.0/1.1] Use mutex to find the multiple instance

    Ok, here is the best explanation I have on this question.

    I have a server application written using C++. Now I try to automate the server to start it automatically. So I write a .Net service to do that.

    It's fine, my service is working fine.

    But there is one issue. Actually my server can't run multiple server using the same IP. So I want to find is there any server running on specific IP.

    So, I used Mutex.

    Here what I have done. First get the each server IP from a data base and on each one test there is any instance going on.

    Code:
    		private bool HasMultipleInstance(string IP)
    		{
    			/*
    			 * No need to acquire or release the Mutex in .Net
    			 * */
    			IPMutex = new Mutex( true, IP + "_mutex_" );
    			//IPMutex.WaitOne();	
    
    			if( IPMutex != null )
    			{
    				EventLog.WriteEntry( "MyService", "Multiple Instances on " + IP );
    				//IPMutex.ReleaseMutex(); 
    				return false;
    			}
    			else
    				return true;
    		}
    What is your guys comment on this. Is that ok? Actually it write an entry to the event log, when a multiple instance is found..

    Thanks a lot
    “victory breeds hatred, the defeated live in pain; happily the peaceful live giving up victory and defeat” - Gautama Buddha

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width