程序只允许运行一个实例的两种方法(C#)

在工作中遇到了程序只能运行一个实例的需求,现将两种方法分享出来


方法1:根据运行中的进程名称判断是否有程序已经在执行了

System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess();
System.Diagnostics.Process[] pros = System.Diagnostics.Process.GetProcessesByName(process.ProcessName);
for (int i = 0; i < pros.Length; i++)
{
	if (process.Id != pros[i].Id) //筛选掉当前的进程
	{
		return;
	}
}
Console.ReadLine();

方法2:根据反射获得的guid来判断是否有程序已经在执行了,此方法个人感觉比方法1要好,推荐使用这种

1.添加命名空间

using System.Runtime.InteropServices;
using System.Threading;
using System.Reflection;

2.main函数外添加成员变量:

static Mutex _mutex;
3.在主函数中添加以下代码:
Boolean mutexflag = false;
Attribute attribute = Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(GuidAttribute));
string guid = ((GuidAttribute)attribute).Value;
_mutex = new Mutex(true, guid, out mutexflag);
if (mutexflag == false)
{
	return;
}
Console.ReadLine();     //假装有程序在运行
_mutex.ReleaseMutex();


猜你喜欢

转载自blog.csdn.net/a519736285/article/details/80689623