• 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()方法中就可以实现..

  • 相关阅读:
    随机过程之第一次出现的期望
    js模板引擎介绍搜集
    qt的安装和debug
    $parse/$eval和$observe/$watch如何区分
    angular controller as syntax vs scope
    Angularjs Controller 间通信机制
    Ng-template寄宿方式
    angularjs移除不必要的$watch
    angularJs项目实战!02:前端的页面分解与组装
    推荐几个可以与PhoneGap很好搭配的UI框架
  • 原文地址:https://www.cnblogs.com/yangjinwang/p/4763663.html
Copyright © 2020-2023  润新知