在WinForm或者Console程序中,可以通过可以遍历所有现在正在执行的进程,如果有同名的进程存在,那么说明这个程序已经启动了一个了,此处就不再启动了。如果没有同名进程的存在,说明这个程序还没有启动过,此时我们可以启动一个。
public static void Main()
{
string strModuleName = System.Diagnostics.Process.GetCurrentProcess().MainModule.ModuleName;
string strProcName = System.IO.Path.GetFileNameWithoutExtension(strModuleName);
// Check if application is running allready, if so do nothing just end.
if ((!(System.Diagnostics.Process.GetProcessesByName(strProcName).Length > 1)))
{
//启动程序
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
或者使用Mutex方式。Mutex是C#自带的一个类,通过下边的代码,可以直接达到想要的效果。
static void Main()
{
bool createNew;
try
{
using (System.Threading.Mutex m = new System.Threading.Mutex(true, "Global\\" + Application.ProductName, out createNew))
{
if (createNew)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
else
{
MessageBox.Show("Only one instance of this application is allowed!");
}
}
}
catch
{
MessageBox.Show("Only one instance of this application is allowed!");
}
}
在Windows Service中,因为是以服务的形式存在,一个服务只能启动一次,不像WinForm程序,WinForm在不同的时间点击多次就会尝试启动多个,Windows Service不会。但是这里也有一种情况,就是Windows Service会涉及到一个定时任务的问题。会使用一个Timer,让其在指定的时间间隔内执行某个方法。比如说,这个windows service设定的是每10分钟执行一次方法A,但是有时候因为网络问题,方法A执行的比较慢,10分钟之内并没有执行完毕。但是此时又达到了Timer的时间间隔设定值,Timer就会再次启动一个线程来执行这个方法,此时如果A方法同时被两个线程执行的话,就会有问题。所以,我们也要防止同一时间内一个方法被多个线程执行。
先检查一下这个进程有没有已经存在,如果已经存在,那么就不再开启一个新的进程。
private object _lockFlag = new object();
private System.Timers.Timer _timer = null;
private bool _threadIsRunning = false;
private ServiceManager _manager = new ServiceManager();
//因为同时会有多个线程来访问这个变量,所以给这个变量进行了加锁操作。
private bool ThreadIsRunning
{
get
{
lock (this._lockFlag) { return this._threadIsRunning; }
}
set
{
lock (this._lockFlag) { this._threadIsRunning = value; }
}
}
//因为Windows Service要进行计划任务,所以就使用了Timer
private void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (this.ThreadIsRunning)
return;
this.ThreadIsRunning = true;
//这个就是上边说到的A方法,里边包含的是windows service的主要操作逻辑。如果不采取措施的话,可能同时被多个Timer启动的线程执行
this._manager.Excecute();
this.ThreadIsRunning = false;
}
protected override void OnStart(string[] args)
{
try
{
Log.Info("service is starting.");
this._timer = new System.Timers.Timer(100000);
this._timer.Enabled = true;
this._timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed);
this._timer.Start();
}
catch (Exception ex)
{
Log.Error(ex);
}
}