多次阻止我的 windows 申请 运行

Prevent my windows application to run multiple times

我在 visual studio 中内置了一个 windows 应用程序,它将部署到具有多个用户的其他 PC,我想防止我的应用程序多次 运行 有什么办法可以以编程方式阻止它?或者以其他方式?

您可以使用此代码段来检查实例是否为 运行,并且可以提醒用户另一个实例为 运行

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

您可以为此目的使用命名互斥锁。命名(!)互斥体是系统范围的同步对象。我在我的项目中使用以下 class(稍微简化)。它在构造函数中创建一个最初无主的互斥锁,并在对象生命周期内将其存储在成员字段中。

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;
    }
  }
}

这个例子展示了如何在程序中使用它。

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();
     }
   }
}