C#实现只允许一个实例运行

string AppName = System.Reflection.Assembly.GetEntryAssembly().GetName().Name;
Process[] processes = System.Diagnostics.Process.GetProcessesByName(AppName);
int pid = Process.GetCurrentProcess().Id;
for (int i = 0; i < processes.Length; i++)
{
    if (pid != processes[i].Id && processes[i].MainModule.FileName == Assembly.GetExecutingAssembly().Location)
    {
        DebugOutput.ProcessMessage(String.Format("[INFO] 应用程序已经在运行中。"));
        Thread.Sleep(100);
        System.Environment.Exit(1);
        return;
    }
}
posted @ 2024-03-26 09:41  qiutian-hao  阅读(37)  评论(0编辑  收藏  举报