张赐荣——一位视障程序员。
赐荣小站: www.prc.cx

張賜榮

张赐荣的技术博客

博客园 首页 新随笔 联系 订阅 管理

C#使用Mutex互斥体禁止程序重复运行


正常情况下,一个进程的执行不会影响其他正在运行的程序实例。然而,一些项目有特殊要求,如使用串口等硬件设备以独占方式,要求其他进程试图使用这个串口设备不允许运行在他们的过程中,这样的程序通常不允许运行同一个程序的多个实例。这就导致了互斥过程的问题。

下面是一种防止打开多个应用程序的常见方法,使用C#互斥锁(Mutex)实现进程只能启动单一实例。
运行结果:首次启动显示“你好赐荣!”,重复运行显示“程序以启动,不能重复运行”。

using System;
using System.Threading;

namespace CRApp
{
    public class Program
    {
        [STAThread]
        static int Main(string[] args)
        {
            if (CheckRunning("ZhangCiRong"))  // 设定程序禁止重复运行,并返回检查当前进程是否重复开启的实例的结果。"identifier"不能与其它程序一样,这是区分互斥所的标识符。
            {
                Console.WriteLine("程序已经运行,不能重复启动。");
            }
            else
            {
                Console.WriteLine("你好赐荣!");
            }
            Console.ReadLine();
            return (0);
        }

        public static bool CheckRunning(string identifier)
        {
            System.Security.Cryptography.MD5CryptoServiceProvider md = new System.Security.Cryptography.MD5CryptoServiceProvider();
            string md5c = BitConverter.ToString(md.ComputeHash(System.Text.Encoding.Default.GetBytes(identifier))).ToLower().Replace("-", "");
            bool isRunning = false;
            new System.Threading.Mutex(true, md5c, out isRunning);  // IsRunning true:表示该互斥体创建成功,之前没有同名互斥体(程序未运行);false:表示创建失败,之前以有同名互斥体(程序已运行)
            md.Dispose();
            return (!isRunning);
        }
    }
}

参考:
https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.mutex?redirectedfrom=MSDN&view=net-6.0#main

posted on 2022-02-19 21:02  张赐荣  阅读(395)  评论(0编辑  收藏  举报

感谢访问张赐荣的技术分享博客!
博客地址:https://cnblogs.com/netlog/
知乎主页:https://www.zhihu.com/people/tzujung-chang
个人网站:https://prc.cx/