Home > Software design >  Prevent my windows application to run multiple times
Prevent my windows application to run multiple times

Time:11-24

I have an windows application built in visual studio that will deploy to other PC's with several users and i want to prevent my application to run multiple times is there any way to prevent it programmatically ? or in other way?

CodePudding user response:

You can use a named mutex for that purpose. A named(!) mutex is a system-wide synchronization object. I use the following class (slightly simplified) in my projects. It creates an initially unowned mutex in the constructor and stores it in a member field during the object lifetime.

public class SingleInstance : IDisposable
{
  private System.Threading.Mutex  _mutex;
  
  // Private default constructor to suppress uncontrolled instantiation.
  private SingleInstance(){}
  
  public SingleInstance(string mutexName)
  {
    if(string.IsNullOrWhiteSpace(mutexName))
      throw new ArgumentNullException("mutexName");
    
    _mutex = new Mutex(false, mutexName);         
  }

  ~SingleInstance()
  {
    Dispose(false);
  }
    
  public bool IsRunning
  {
    get
    {
      // requests ownership of the mutex and returns true if succeeded
      return !_mutex.WaitOne(1, true);
    }    
  }

  public void Dispose()
  {
    GC.SuppressFinalize(this);
    Dispose(true);
  }

  protected virtual void Dispose(bool disposing)
  {
    try
    {
      if(_mutex != null)
        _mutex.Close();
    }
    catch(Exception ex)
    {
      Debug.WriteLine(ex);
    }
    finally
    {
      _mutex = null;
    }
  }
}

This example shows, how to use it in a program.

static class Program
{
   static SingleInstance _myInstance = null;

   [STAThread]
   static void Main()
   {
     // ...

     try
     {
       // Create and keep instance reference until program exit
       _myInstance = new SingleInstance("MyUniqueProgramName");

       // By calling this property, this program instance requests ownership 
       // of the wrapped named mutex. The first program instance gets and keeps it 
       // until program exit. All other program instances cannot take mutex
       // ownership and exit here.
       if(_myInstance.IsRunning)
       {
         // You can show a message box, switch to the other program instance etc. here

         // Exit the program, another program instance is already running
         return;
       }

       // Run your app

     }
     finally
     {
       // Dispose the wrapper object and release mutex ownership, if owned
       _myInstance.Dispose();
     }
   }
}

CodePudding user response:

You can use this snippet to check whether instance is running or not and can alert user that another instance is running

   static bool IsRunning()
{
    return Process.GetProcesses().Count(p => p.ProcessName.Contains(Assembly.GetExecutingAssembly().FullName.Split(',')[0]) && !p.Modules[0].FileName.Contains("vshost")) > 1;
}
  • Related