控制台程序 如何控制不让它启动两个
就是我现在要做一个  dos下运行的.exe文件
不能让它同时起动两个 

解决方案 »

  1.   


    using System;
    using System.Collections.Generic;
    using System.Threading;namespace ConsoleApplication1
    {
        class Program
        {
            static Mutex mutex;
            static void Main(string[] args)
            {
                //
                // check whether 'MyMutex' is already created. if so, return immediately
                //
                bool createNew;
                mutex = new Mutex(false, "MyMutex", out createNew);
                if (!createNew) return;            //
                // your code goes here
                //
                Console.WriteLine("I am the first and the only instance. Press enter to exit...");
                Console.ReadLine();
            }
        }
    }
    Putting a  in the registry is not a good solution.
    If the program does not exit normally (for example being killed), the  remains in the registry.
    And the program can't run anymore.In contrast, Mutex has a sense of ownership. When a process terminates, its ownership to the mutex is abandoned. 
    Subsequent program has no problems to claim the mutex.