How to determine if a previous instance of my application is running?

后端 未结 10 1495
梦谈多话
梦谈多话 2020-12-05 10:31

I have a console application in C# in which I run various arcane automation tasks. I am well aware that this should really be a Windows Service since it nee

10条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-05 10:55

    Jeroen already answered this, but the best way by far is to use a Mutex... not by Process. Here's a fuller answer with code.

    Mutex mutex;
    
    try
    {
       mutex = Mutex.OpenExisting("SINGLEINSTANCE");
       if (mutex!= null)
       {
          Console.WriteLine("Error : Only 1 instance of this application can run at a time");
          Application.Exit();
       }
    }
    catch (WaitHandleCannotBeOpenedException ex)
    {
       mutex  = new Mutex(true, "SINGLEINSTANCE");
    }
    

    Also bear in mind that you need to run your Application in some sort of Try{} Finally{} block. Otherwise if you're application crashes without releasing the Mutex then you may not be able to restart it again later.

提交回复
热议问题