允许两个应用程序实例运行

Scr*_*uck 3 c#

我理解如何使用互斥锁强制应用程序的单个实例,这就是我使用的.

我的一些用户要求我允许运行多个实例.我不想删除控制代码,因为我可以将其视为灾难的处方,因为多个实例可能正在写入相同的文件,日志等.

如果实例的数量限制为两个,我也许可以处理.我目前的想法是允许第一个以某种形式的只读模式运行作为活动的一个和第二个.

那么我如何控制实例数量不超过两个呢?

谢谢

dri*_*iis 12

听起来你想要一个命名为2的系统信号量.

这是一个例子:

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

信号量允许许多并发线程访问资源,当使用名称创建它时,它是一个操作系统范围的信号量,因此它很适合您的目的.