如何防止程序的多个实例同时运行?

时间:2012-11-26 10:02:21

标签: c#

所以我创建了一个程序(不使用表单),因此它是一个干净的类,而不是表单。 因此,当程序启动时,我希望它检查进程,如果找到另一个进程,则自行终止。我试过这个......

static void checkDupe()
{
    string RunningProcess = Process.GetCurrentProcess().ProcessName;
    Process[] processes = Process.GetProcessesByName(RunningProcess);

    if (processes.Length > 1)
    {
        Process.GetCurrentProcess().Kill();
    }
}

4 个答案:

答案 0 :(得分:4)

使用Mutex

class Program
{
    static Mutex _m;

    static bool IsSingleInstance()
    {
    try
    {
        // Try to open existing mutex.
        Mutex.OpenExisting("PERL");
    }
    catch
    {
        // If exception occurred, there is no such mutex.
        Program._m = new Mutex(true, "PERL");

        // Only one instance.
        return true;
    }
    // More than one instance.
    return false;
    }

    static void Main()
    {
    if (!Program.IsSingleInstance())
    {
        Console.WriteLine("More than one instance"); // Exit program.
    }
    else
    {
        Console.WriteLine("One instance"); // Continue with program.
    }
    // Stay open.
    Console.ReadLine();
    }
}

以上示例摘自:

http://www.dotnetperls.com/mutex

答案 1 :(得分:0)

它按名称

返回正在运行的程序的实例
private static Process RunningInstance()
{
    var current = Process.GetCurrentProcess();
    var procName = current.ProcessName.Replace(@".vshost", string.Empty);
    var processes = Process.GetProcessesByName(procName);

    return processes.FirstOrDefault(t => t.Id != current.Id && current.SessionId == t.SessionId);
}

答案 2 :(得分:0)

这是从我的另一个答案复制的:Syncing between multiple instances of the same program

Bellow你可以找到简化检查多个实例的代码,并允许将起始参数从第二个实例转移到第一个实例。

    /// <summary>
        /// Enforces single instance for an application.
        /// </summary>
        public class SingleInstance : IDisposable
        {
            #region Fields

            /// <summary>
            /// The synchronization context.
            /// </summary>
            private readonly SynchronizationContext synchronizationContext;

            /// <summary>
            /// The disposed.
            /// </summary>
            private bool disposed;

            /// <summary>
            /// The identifier.
            /// </summary>
            private Guid identifier = Guid.Empty;

            /// <summary>
            /// The mutex.
            /// </summary>
            private Mutex mutex;

            #endregion

            #region Constructors and Destructors

            /// <summary>
            /// Initializes a new instance of the <see cref="SingleInstance"/> class.
            /// </summary>
            /// <param name="identifier">
            /// An identifier unique to this application.
            /// </param>
            /// <param name="args">
            /// The command line arguments.
            /// </param>
            public SingleInstance(Guid identifier, IEnumerable<string> args)
            {
                this.identifier = identifier;

                bool ownsMutex;
                this.mutex = new Mutex(true, identifier.ToString(), out ownsMutex);

                this.synchronizationContext = SynchronizationContext.Current;

                this.FirstInstance = ownsMutex;

                if (this.FirstInstance)
                {
                    this.ListenAsync();
                }
                else
                {
                    this.NotifyFirstInstance(args);
                }
            }

            /// <summary>
            /// Initializes a new instance of the <see cref="SingleInstance"/> class.
            /// </summary>
            /// <param name="identifier">
            /// An identifier unique to this application.
            /// </param>
            public SingleInstance(Guid identifier)
                : this(identifier, null)
            {
            }

            #endregion

            #region Public Events

            /// <summary>
            /// Event raised when arguments are received from successive instances.
            /// </summary>
            public event EventHandler<OtherInstanceCreatedEventArgs> OtherInstanceCreated;

            #endregion

            #region Public Properties

            /// <summary>
            /// Gets a value indicating whether this is the first instance of this application.
            /// </summary>
            public bool FirstInstance { get; private set; }

            #endregion

            #region Implemented Interfaces

            #region IDisposable

            /// <summary>
            /// The dispose.
            /// </summary>
            public void Dispose()
            {
                this.Dispose(true);
                GC.SuppressFinalize(this);
            }

            #endregion

            #endregion

            #region Methods

            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            /// <param name="disposing">
            /// True if managed resources should be disposed; otherwise, false.
            /// </param>
            protected virtual void Dispose(bool disposing)
            {
                if (this.disposed)
                {
                    return;
                }

                if (disposing)
                {
                    if (this.mutex != null && this.FirstInstance)
                    {
                        this.mutex.WaitOne();
                        this.mutex.ReleaseMutex();
                        this.mutex = null;
                    }
                }

                this.disposed = true;
            }

            /// <summary>
            /// Fires the OtherInstanceCreated event.
            /// </summary>
            /// <param name="arguments">
            /// The arguments to pass with the <see cref="OtherInstanceCreatedEventArgs"/> class.
            /// </param>
            protected virtual void OnOtherInstanceCreated(OtherInstanceCreatedEventArgs arguments)
            {
                EventHandler<OtherInstanceCreatedEventArgs> handler = this.OtherInstanceCreated;

                if (handler != null)
                {
                    handler(this, arguments);
                }
            }

            /// <summary>
            /// Listens for arguments on a named pipe.
            /// </summary>
            private void Listen()
            {
                try
                {
                    using (var server = new NamedPipeServerStream(this.identifier.ToString()))
                    {
                        using (var reader = new StreamReader(server))
                        {
                            server.WaitForConnection();
                            var arguments = new List<string>();

                            while (server.IsConnected)
                            {
                                arguments.Add(reader.ReadLine());
                            }

                            this.synchronizationContext.Post(o => this.OnOtherInstanceCreated(new OtherInstanceCreatedEventArgs(arguments)), null);                        
                        }
                    }

                    // start listening again.
                    this.Listen();
                }
                catch (IOException)
                {
                    // Pipe was broken, listen again.
                    this.Listen();
                }          
            }

            /// <summary>
            /// Listens for arguments being passed from successive instances of the applicaiton.
            /// </summary>
            private void ListenAsync()
            {
                Task.Factory.StartNew(this.Listen, TaskCreationOptions.LongRunning);
            }

            /// <summary>
            /// Passes the given arguments to the first running instance of the application.
            /// </summary>
            /// <param name="arguments">
            /// The arguments to pass.
            /// </param>
            private void NotifyFirstInstance(IEnumerable<string> arguments)
            {
                try
                {
                    using (var client = new NamedPipeClientStream(this.identifier.ToString()))
                    {
                        using (var writer = new StreamWriter(client))
                        {
                            client.Connect(200);

                            if (arguments != null)
                            {
                                foreach (string argument in arguments)
                                {
                                    writer.WriteLine(argument);
                                }
                            }
                        }
                    }
                }
                catch (TimeoutException)
                {
                    // Couldn't connect to server
                }
                catch (IOException)
                {
                    // Pipe was broken
                }
            }



 #endregion
    }

/// <summary>
/// Holds a list of arguments given to an application at startup.
/// </summary>
public class OtherInstanceCreatedEventArgs : EventArgs
{
    #region Constructors and Destructors

    /// <summary>
    /// Initializes a new instance of the <see cref="OtherInstanceCreatedEventArgs"/> class.
    /// </summary>
    /// <param name="args">
    /// The command line arguments.
    /// </param>
    public OtherInstanceCreatedEventArgs(IEnumerable<string> args)
    {
        this.Args = args;
    }

    #endregion

    #region Public Properties

    /// <summary>
    /// Gets the startup arguments.
    /// </summary>
    public IEnumerable<string> Args { get; private set; }

    #endregion
}

然后在您的主类中,您可以创建将继续运行的类的实例。您可以检查FirstInstance属性是否创建了其他实例,并获得OtherInstanceCreated事件创建的其他实例的通知。

答案 3 :(得分:0)

相同的mutex想法,但更简单的代码:

        bool SingleInstance;
        var mut = new Mutex(true,"UniqueName", out SingleInstance);
        if (SingleInstance) {
           //Run
        } else {
           //Exit
        }

当应用程序存在时,互斥锁被破坏,无需释放或处置它或任何东西。

(AFAIK)