在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());
}
} 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!");
}
} 先检查一下这个进程有没有已经存在,如果已经存在,那么就不再开启一个新的进程。
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);
}
}原文:http://blog.csdn.net/sundacheng1989/article/details/28388441