【问题标题】:What is the safest way to prevent multiple instances of a program?防止程序出现多个实例的最安全方法是什么?
【发布时间】:2012-01-07 00:30:58
【问题描述】:

我试图阻止我的程序在任何给定时间运行多个实例。我已经阅读了有关使用互斥锁和 Windows 事件的信息,但是这两个线程都有几年的历史了,我很好奇 .net4 是否有更简单、更优雅的方式来处理这个问题?我以为我已经阅读了允许您通过属性拒绝多个实例的表单设置?有人可以阐明防止程序出现多个实例的最安全和/或最简单的方法是什么?

【问题讨论】:

  • 最安全的方法是使用 .NET 中的内置支持,WindowsFormsApplicationBase.IsSingleInstance 属性。很难猜测它是否合适,您没有花太多精力描述您的确切需求。不,过去 5 年没有任何变化。
  • 创建一个命名事件。看看如何做到这一点[这里][1] [1]:stackoverflow.com/questions/447546/…
  • 汉斯,如果您将该评论作为实际答案,我将奖励您选择的答案。

标签: c# .net mutex multiple-instances


【解决方案1】:

最安全的方法是使用 .NET 中的内置支持,WindowsFormsApplicationBase.IsSingleInstance 属性。很难猜测它是否合适,您没有花太多精力描述您的确切需求。不,过去 5 年没有任何变化。 – Hans Passant 1 月 7 日 0:38

这是最好的答案,但 Hans 没有将其作为答案提交。

【讨论】:

    【解决方案2】:

    在 VB 中,您可以在项目级别(属性 > 常规)为 Winforms 项目设置此项。

    在 C# 中,您可以使用类似于此的代码.. 当然需要转换..

    Dim tGrantedMutexOwnership As Boolean = False
    Dim tSingleInstanceMutex As Mutex = New Mutex(True, "MUTEX NAME HERE", tGrantedMutexOwnership)
    
    If Not tGrantedMutexOwnership Then
    '
    ' Application is already running, so shut down this instance
    '
    Else
    ' 
    ' No other instances are running
    '
    End If
    

    哎呀,我忘了提到您需要在 Application.Run() 调用之后放置 GC.KeepAlive(tSingleInstanceMutex)

    【讨论】:

      【解决方案3】:
      using System;
      using System.Collections.Generic;
      using System.Diagnostics;
      using System.Linq;
      using System.Windows.Forms;
      
      namespace YourNameSpaceGoesHere
      {
          static class Program
          {
              /// <summary>
              /// The main entry point for the application.
              /// </summary>
              [STAThread]
              static void Main()
              {
      
                  if (Process.GetProcessesByName("YourFriendlyProcessNameGoesHere").Length > 1)
                  {
                      MessageBox.Show(Application.ProductName + " already running!");
                      Application.ExitThread();
                  }
                  else
                  {
                      Application.EnableVisualStyles();
                      Application.SetCompatibleTextRenderingDefault(false);
                      Application.Run(new YourStartUpObjectFormNameGoesHere());
                  }
      
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-03
        • 2018-11-07
        • 1970-01-01
        • 2010-10-13
        • 2012-04-06
        相关资源
        最近更新 更多