C# 控制台程序如何防止启动多个实例

 

=========================================================================================================

#region 判断当前程序是否启动,如果已启动则退出,保证只有一个实例启动
bool blnIsRunning;
Mutex mutexApp = new Mutex(false, Assembly.GetExecutingAssembly().FullName, out blnIsRunning);
Console.WriteLine(string.Format("当前运行程序集名称:{0}!", Assembly.GetExecutingAssembly().FullName));
tempLog.Info(string.Format("当前运行程序集名称:{0}!", Assembly.GetExecutingAssembly().FullName));
if (!blnIsRunning)
{
Console.WriteLine("程序已经运行!");
tempLog.Info("程序已经运行!");
return;
}
#endregion

============================================================================================================

#region 懒人的办法,不建议使用

Process[] processes = Process.GetProcessesByName("LoanMatching.DataSys.LoanFormalConsole");

if (processes.Length > 1)
{
Console.WriteLine("已经存在运行中的实例,程序终止");
LogHelper.Instance.Log.Info(string.Format("{0}已经存在运行中的实例,程序终止", DateTime.Now.ToLongTimeString()));
return;
}
else
{
Console.WriteLine("程序将正常运行");
}

#endregion

================================================================================================================

// 以下两种方式是 我在网上搜索到的,没试行不行

 

             //保证同时只有一个客户端在运行   
            //System.Threading.Mutex mutexMyapplication = new System.Threading.Mutex(false, "OnePorcess.exe");
            //if (!mutexMyapplication.WaitOne(100, false))
            //{
            //    MessageBox.Show("程序" + Application.ProductName + "已经运行!", Application.ProductName,
            //    MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    return;
            //}
代码:
//=====判断进程法:(修改程序名字后依然能执行)=====
            //Process current = Process.GetCurrentProcess();
            //Process[] processes = Process.GetProcessesByName(current.ProcessName);
            //foreach (Process process in processes)
            //{
            //    if (process.Id != current.Id)
            //    {
            //        if (process.MainModule.FileName
            //        == current.MainModule.FileName)
            //        {
            //            MessageBox.Show("程序已经运行!", Application.ProductName,
            //            MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            //            return;
            //        }
            //    }
            //}     

只需要把需要的方法代码放在Void Main()方法中就可以实现..

转载于:https://www.cnblogs.com/yangjinwang/p/4763663.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值