代码之家  ›  专栏  ›  技术社区  ›  C. Dragon 76

是否在.NET中阻止给定应用程序的多个实例?

  •  114
  • C. Dragon 76  · 技术社区  · 16 年前

    在.NET中,防止应用程序的多个实例同时运行的最佳方法是什么?如果没有“最佳”技术,那么在每个解决方案中应该考虑哪些注意事项?

    22 回复  |  直到 16 年前
        1
  •  139
  •   Omar Kooheji    11 年前

    http://odetocode.com/Blogs/scott/archive/2004/08/20/401.aspx

    [STAThread]
    static void Main() 
    {
       using(Mutex mutex = new Mutex(false, "Global\\" + appGuid))
       {
          if(!mutex.WaitOne(0, false))
          {
             MessageBox.Show("Instance already running");
             return;
          }
    
          Application.Run(new Form1());
       }
    }
    
    private static string appGuid = "c0a76b5a-12ab-45c5-b9d9-d693faa6e7b9";
    
        2
  •  17
  •   Ian Boyd    15 年前
    if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1)
    {
      AppLog.Write("Application XXXX already running. Only one instance of this application is allowed", AppLog.LogMessageType.Warn);
      return;
    }
    
        3
  •  16
  •   Alex Seibar    12 年前

    public class Program
    {
        static System.Threading.Mutex singleton = new Mutex(true, "My App Name");
    
        static void Main(string[] args)
        {
            if (!singleton.WaitOne(TimeSpan.Zero, true))
            {
                //there is already another instance running!
                Application.Exit();
            }
        }
    }
    
        4
  •  7
  •   bdukes Jon Skeet    16 年前
        5
  •  5
  •   C. Dragon 76    16 年前

        6
  •  4
  •   Doliveras    13 年前

    enter image description here

        7
  •  4
  •   HypeZ    10 年前

    private static string appGuid = "WRITE AN UNIQUE GUID HERE";
    private static Mutex mutex;
    

    bool mutexCreated;
    mutex = new Mutex(true, "Global\\" + appGuid, out mutexCreated);
    if (mutexCreated)
        mutex.ReleaseMutex();
    
    if (!mutexCreated)
    {
        //App is already running, close this!
        Environment.Exit(0); //i used this because its a console app
    }
    

        10
  •  2
  •   MADMap    16 年前

        11
  •  2
  •   user5289350    9 年前

    using System.Diagnostics;
    

    void Main()

     if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length >1)
                    return;
    

        14
  •  1
  •   Max    11 年前

    Private Shared Sub Main()
        Using mutex As New Mutex(False, appGuid)
            If Not mutex.WaitOne(0, False) Then
                  MessageBox.Show("Instance already running", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error)
                Return
            End If
    
            Application.Run(New Form1())
        End Using
    End Sub
    

    private static void Main()
    {
        using (Mutex mutex = new Mutex(false, appGuid)) {
            if (!mutex.WaitOne(0, false)) {
                MessageBox.Show("Instance already running", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
    
            Application.Run(new Form1());
        }
    }
    
        15
  •  1
  •   Bitterblue    10 年前

    private static Bitmap randomName = new Bitmap("my_image.jpg");
    
        16
  •  1
  •   Kasper Jensen    9 年前

    http://www.c-sharpcorner.com/UploadFile/f9f215/how-to-restrict-the-application-to-just-one-instance/

    public partial class App : Application  
    {  
        private static Mutex _mutex = null;  
    
        protected override void OnStartup(StartupEventArgs e)  
        {  
            const string appName = "MyAppName";  
            bool createdNew;  
    
            _mutex = new Mutex(true, appName, out createdNew);  
    
            if (!createdNew)  
            {  
                //app is already running! Exiting the application  
                Application.Current.Shutdown();  
            }  
    
        }          
    }  
    

    x:Class="*YourNameSpace*.App"
    StartupUri="MainWindow.xaml"
    Startup="App_Startup"
    
        17
  •  1
  •   Divins Mathew Pentium10    7 年前

    StreamWriter

    System.IO.File.StreamWriter OpenFlag = null;   //globally
    

    try
    {
        OpenFlag = new StreamWriter(Path.GetTempPath() + "OpenedIfRunning");
    }
    catch (System.IO.IOException) //file in use
    {
        Environment.Exit(0);
    }
    
        18
  •  0
  •   Tomer Gabel    16 年前
        19
  •  0
  •   Derek Wade    9 年前

    using System.Diagnostics;
    ....
    [STAThread]
    static void Main()
    {
    ...
            int procCount = 0;
            foreach (Process pp in Process.GetProcesses())
            {
                try
                {
                    if (String.Compare(pp.MainModule.FileName, Application.ExecutablePath, true) == 0)
                    {
                        procCount++;                        
                        if(procCount > 1) {
                           Application.Exit();
                           return;
                        }
                    }
                }
                catch { }
            }
            Application.Run(new Form1());
    }
    
        20
  •  0
  •   Sachin    8 年前
    [STAThread]
    static void Main()                  // args are OK here, of course
    {
        bool ok;
        m = new System.Threading.Mutex(true, "YourNameHere", out ok);
    
        if (! ok)
        {
            MessageBox.Show("Another instance is already running.");
            return;
        }
    
        Application.Run(new Form1());   // or whatever was there
    
        GC.KeepAlive(m);                // important!
    }
    

    Ensuring a single instance of .NET Application

    Single Instance Application Mutex

    Jon Skeet's FAQ on C# GC.KeepAlive

        22
  •  0
  •   Tono Nam    5 年前

        public static void PreventMultipleInstance(string applicationId)
        {
            // Under Windows this is:
            //      C:\Users\SomeUser\AppData\Local\Temp\ 
            // Linux this is:
            //      /tmp/
            var temporaryDirectory = Path.GetTempPath();
    
            // Application ID (Make sure this guid is different accross your different applications!
            var applicationGuid = applicationId + ".process-lock";
    
            // file that will serve as our lock
            var fileFulePath = Path.Combine(temporaryDirectory, applicationGuid);
    
            try
            {
                // Prevents other processes from reading from or writing to this file
                var _InstanceLock = new FileStream(fileFulePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
                _InstanceLock.Lock(0, 0);
                MonoApp.Logger.LogToDisk(LogType.Notification, "04ZH-EQP0", "Aquired Lock", fileFulePath);
    
                // todo investigate why we need a reference to file stream. Without this GC releases the lock!
                System.Timers.Timer t = new System.Timers.Timer()
                {
                    Interval = 500000,
                    Enabled = true,
                };
                t.Elapsed += (a, b) =>
                {
                    try
                    {
                        _InstanceLock.Lock(0, 0);
                    }
                    catch
                    {
                        MonoApp.Logger.Log(LogType.Error, "AOI7-QMCT", "Unable to lock file");
                    }
                };
                t.Start();
    
            }
            catch
            {
                // Terminate application because another instance with this ID is running
                Environment.Exit(102534); 
            }
        }