开发者

Allow Two Instances of Application to Run

开发者 https://www.devze.com 2023-03-26 12:24 出处:网络
I understand how to force a single instance of an application usin开发者_Python百科g a mutex and this is what I use.

I understand how to force a single instance of an application usin开发者_Python百科g a mutex and this is what I use.

Several of my users have asked me to allow multiple instances to run. I don't want to remove the control code as I can see it as a recipe for disaster since multiple instances could be writing to the same files, log and so on.

I perhaps could handle things if the number of instances is limited to two. My current idea is to allow the first one to run as the active one and a second in some form of read-only mode.

So how would I control the number of instances to no more than two?

Thanks


It sounds like you want a named system Semaphore with a count of 2.

Here is an example:

class Program
{
    private const int MaxInstanceCount = 2;
    private static readonly Semaphore Semaphore = new Semaphore(MaxInstanceCount, MaxInstanceCount, "CanRunTwice");

    static void Main(string[] args)
    {            
        if (Semaphore.WaitOne(1000))
        {
            try
            {
                Console.WriteLine("Program is running");
                Console.ReadLine();
            }
            finally
            {
                Semaphore.Release();
            }
        }
        else
        {
            Console.WriteLine("I cannot run, too many instances are already running");
            Console.ReadLine();
        }
    }
}

A Semaphore allows a number of concurrent threads to access a resource, and when it is created with a name, it is a operating-system-wide semaphore, so it fits your purpose well.


bool IsFree = false;


Mutex mutex = new Mutex(true, "MutexValue1", out IsFree);

if(!IsFree)
    mutex = new Mutex(true, "MutexValue2", out IsFree);

if(!IsFree)
{
    //two instances are already running
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号