我正在使用C#进行Mono和Linux项目。我必须确保不能运行同一程序的两个实例。所以,我有一个看起来像这样的函数
private static bool CanRun()
{
bool canRun = true;
string currProcessName = Process.GetCurrentProcess().ProcessName;
string currProcessWorkingDir = Process.GetCurrentProcess().MainModule.FileName;
int currProcessId = Process.GetCurrentProcess().Id;
Process[] matchingProcesses = null;
try
{
// Find processes that match our own process name.
matchingProcesses = Process.GetProcessesByName(currProcessName);
if ( matchingProcesses.Length == 1)
{
// The matching process list will contain ourselves, so filter out ourself by ID. Then,
// check the working folder for an exact match to ourselves.
if (matchingProcesses.Any(matchingProcess =>
matchingProcess.ProcessName == currProcessName))
{
canRun = false;
}
}
}
catch (System.InvalidOperationException) { }
catch (System.ComponentModel.Win32Exception) { }
return canRun;
}
我的问题是,matchingProcesses = Process.GetProcessesByName(currProcessName)始终返回一个数组。这意味着当我有一个正在运行的进程实例时,当我尝试运行第二个实例时,我仍然得到一个实例数组,因此我的函数失败了。关于我可能做错的任何建议吗?
类似这样的方法应该起作用:
private static bool CanRun2()
{
var canRun = true;
try
{
var currProcess = Process.GetCurrentProcess();
var currProcessName = currProcess.ProcessName;
var matchingProcesses = Process.GetProcessesByName(currProcessName);
canRun = !matchingProcesses.Any((Process p) => p.Id != currProcess.Id);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
canRun = false;
}
return canRun;
}
注意:请记住ProcessName
是相当通用的,在这种情况下会是mono-sgen32
或mono-sgen64
,如果您正在运行其他mono
应用,则必须添加其他检查...