繁体   English   中英

如何创建应用程序的第二个实例?

[英]How can I create a second instance of my application?

我希望为启动时通过命令行参数传递给它的每个文件路径创建我的应用程序的新实例。

现在我在主窗口的构造函数中有这个:

if (args.Length > 0)
        {
            for (int i = 0; i < args.Length; i++)
            {
                string arg = args[i];

                if (File.Exists(arg))
                {
                    if (i > 0)
                        Process.Start(System.Reflection.Assembly.GetExecutingAssembly().Location, arg);
                    else
                        OpenFile(arg);
                }
            }
        }

但是,现在我的程序似乎会创建自己的新实例,直到我的计算机运行我们的内存为止。 看到什么地方了吗

- 编辑 -

Args来自对Appplication.OnStartup事件的重写。

删除对if (args.Length > 0)的检查,因为for循环将解决这一问题。 如果需要跳过arg 0(如SLaks所建议),只需将for循环更改为int i = 1

请注意,如果您始终将参数传递给子流程,并且您的检查基于它们的任何参数,则将无限递归。

因此,此行应更改:

if (i > 0)
    // Spawn new process, passing the argument

至:

if (i > 1)
    // Spawn new process, passing the argument

同样,此代码相当混乱,如此处答案所证明的那样。 这是更简单的代码:

foreach (string arg in args.Skip(2)) // Just Skip(1) if it turns out args[0] != this.exe
    Process.Start(System.Reflection.Assembly.GetExecutingAssembly().Location, arg);

if (args.Length > 1) // > 0 if it turns out args[0] != this.exe
    OpenFile(args[1]);

更改为

Process.Start(typeof(MainWindow).Assembly.Location, "\"" + arg + "\"");

(用引号引起来)

如果arg来自带空格的带引号的路径,则将其传递给Process.Start会将未带引号的值作为两个参数传递。 您需要在其两边加上引号,以确保仅得到一个参数。

更改第一个参数将使其更短更快一些,但不会改变行为。

答:我是个白痴。

为了进行测试,我对一些参数进行了硬编码,然后生成了新的实例。

可以通过计算机屏幕随意指点,嘲笑或向我扔鸡蛋。

如果您的目标是允许所有处理并发运行,为什么不只使用线程呢?

foreach (var i in args) {
    new Thread(delegate {
        try { OpenFile(i); }
        catch (Exception e) { Console.WriteLine("Error processing file {0}: {1}",
                                                i, e.ToString()); }
    }).Start();
}

暂无
暂无

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

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