对有窗口的程序,控制只运行一个实例比较容易。但对于运行在后台,设置成任务计划的程序来说,要控制只运行一个实例,就要多费点小小功夫。下面分享下我的代码:希望对大家有点帮助。
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Reflection;
namespace OneInstance
{
static class Program
{
[STAThread]
static void Main()
{
Process instance = RunningInstance();
if (instance != null)
{
return;
}
//Start your transaction code here
}
public static Process RunningInstance()
{
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(current.ProcessName);
foreach (Process process in processes)
{
if (process.Id != current.Id)
{
if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") ==
current.MainModule.FileName)
{
return process;
}
}
}
return null;
}
}
}
浙公网安备 33010602011771号