如何确定如果我的应用程序的previous实例运行? [英] How to determine if a previous instance of my application is running?
问题描述
我在C#中的控制台应用程序中,我运行各种神秘的自动化任务。我很清楚地知道,这应该是一个真正的 Windows服务,因为它需要连续运行,但我的不要想这样做,在这个时候。 (所以,不建议作为一个答案)。
在此期间,我需要一些示例C#code,让我来决定,如果有已经运行的应用程序的一个实例。
在老VB6.0日子里,我会用程序prevInstance()
我希望能够做到这一点在我的主要方法:
静态无效的主要()
{
如果(!MyApp.IsAlreadyRunning())
{
而(真)
{
RockAndRollAllNightAndPartyEveryDay();
}
}
}
的Jeroen已经回答了这一点,但迄今为止最好的方法是使用一个互斥......不是过程。下面是与code更全面的答案。
互斥互斥;
尝试
{
互斥= Mutex.OpenExisting(SINGLEINSTANCE);
如果(互斥!= NULL)
{
Console.WriteLine(错误:这个应用程序可以同时运行的只有一个实例);
Application.Exit();
}
}
赶上(WaitHandleCannotBeOpenedException前)
{
互斥=新的互斥(真的,SINGLEINSTANCE);
}
另外请记住,你需要以某种尝试{}最后{}块中运行应用程序。否则,如果你的应用程序崩溃而不释放互斥,那么你可能无法稍后再重新启动它。
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 needs to run continuously, but I don't want to do that at this time. (So, don't suggest that as an answer).
In the meantime, I need some sample C# code that will allow me to determine if there's already an instance of the Application running.
In the old VB6.0 days, I would have used App.PrevInstance()
I want to be able to do this in my Main method:
static void Main()
{
if(!MyApp.IsAlreadyRunning())
{
while(true)
{
RockAndRollAllNightAndPartyEveryDay();
}
}
}
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.
这篇关于如何确定如果我的应用程序的previous实例运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!