繁体   English   中英

启动同一个exe的多个实例

[英]launching multiple instances of same exe

我正在尝试运行一个用C#编写的桌面程序。 我在同一台计算机上创建了多个用户以从Remote Desktop.访问Remote Desktop.

我可以从同一用户的角度成功启动多个实例,但我的目标是允许多个用户从他们自己的角度执行多个可执行文件。

我还为每个用户桌面上的每个可执行文件创建了不同的文件夹。

我可以从第一个用户的角度成功启动一个可执行文件。 但不能从第二个用户的角度执行相同的可执行文件,反之亦然。

可执行文件在第二次执行时停止工作。 日志如下:

<ProblemSignatures>

<EventType>CLR20r3</EventType>

<Parameter0>MyExecutable.exe</Parameter0>

<Parameter1>1.0.3.30</Parameter1>

<Parameter2>56e6a1d2</Parameter2>

<Parameter3>mscorlib</Parameter3>

<Parameter4>4.6.1055.0</Parameter4>

<Parameter5>563c0eac</Parameter5>

<Parameter6>157f</Parameter6>

<Parameter7>12e</Parameter7>

<Parameter8>System.UnauthorizedAccess</Parameter8>

</ProblemSignatures>

我想我已经找到了答案。 问题是我的代码使用互斥锁来阻止启动另一个实例。 它看起来像这样并且在从单个用户的角度启动时按预期工作,通过给出无法创建另一个实例的消息:

 private static string appGuid = "39E8A84A-A531-4399-9B55-B480CB1C9B1D";
        //test
        [STAThread]
        static void Main()
        {
            using (Mutex mutex = new Mutex(false, "Global\\" + appGuid))
            {
                bool CheckAnotherInstance = true;
                if (CheckAnotherInstance && !mutex.WaitOne(0, false))
                {
                    MessageBox.Show("Only one executable can be run at the same time");
                    return;
                }

                RunProgram();
            }
        }

但是,即使 CheckAnotherInstance 变量为 false,从第二个用户的角度再次启动时,它也没有给出预期的消息。

我已经重新组织了如下代码,现在它在 CheckAnotherInstance 为假时按预期工作。 代码是这样的:

    private static string appGuid = "39E8A84A-A531-4399-9B55-B480CB1C9B1D";
        //test
        [STAThread]
        static void Main()
        {
            bool CheckAnotherInstance = false;
            if (CheckAnotherInstance)
            {
                using (Mutex mutex = new Mutex(false, "Global\\" + appGuid))
                {
                    if (!mutex.WaitOne(0, false))
                    {
                        MessageBox.Show("Only one executable can be run at the same time");
                        return;
                    }
                    RunMainProgram();
                }
            }
            else
            {
                RunMainProgram();
            }
        }

        private static void RunMainProgram()
        {    
            RunProgram();
        }

您可以防止单个用户运行多个实例,但仍允许多个用户分别运行单个实例。 这是在没有太多额外努力的情况下实现的。

以下代码段将当前用户名附加到您正在获取的互斥锁的名称上。

string userName = System.Threading.Thread.CurrentPrincipal.Identity.Name;
using (Mutex mutex = new Mutex(false, "Global\\" + appGuid + userName))
{
    // do your things
}

如果您想停止从多个实例运行您的 exe(独立于 Windows 用户),您也可以使用以下代码

Dim ProcessName() As Process = Process.GetProcessesByName("MyExe")
If ProcessName.Length > 1 Then
        Messagebox.show "Exe is already running on another instance"
        End
End If

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM