【问题标题】:Is it possible to run multiple commands through one process?是否可以通过一个进程运行多个命令?
【发布时间】:2019-08-09 17:59:06
【问题描述】:

我有一个使用 System.Diagnostics.Process 向 cmd.exe 发送命令的函数,但是我需要循环遍历该命令的一组参数,并且每个循环都会打开一个新的 cmd.exe,它使用了很多不必要的 cpu力量。

目前我正在使用一个 for 循环,该循环递增到列表中的下一项以传递给 ProcessStartInfo。我需要在自己的行上调用每个参数。 IE。 /C myFunction.exe 我的列表[0] /C myFunction.exe 我的列表[1] ...等

我当前的代码通过在 cmd.exe 中调用的 myFunction.exe 将 MyList 中的值设置为 0-24,给定外部 for 循环。

            Process process = new Process();
            ProcessStartInfo StartInfo = new ProcessStartInfo();
            StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            StartInfo.FileName = "cmd.exe";
            for (int j = 0; j < 25; j++)
            {
                for (int i = 0; i < Device_Numbers.Count; i++)
                {
                    StartInfo.Arguments = "/C myFunction.exe " + i + " = " + j;
                    process.StartInfo = StartInfo;
                    process.Start();
                }
                Thread.Sleep(2000);
            }

对 cmd.exe 的调用有效,但是它会为通过 i 的每次迭代打开一个新的 cmd.exe 窗口,如果我可以打开一个窗口并在那个窗口中迭代所有 i 会更好。

【问题讨论】:

  • 为什么需要命令窗口?可以不直接启动myFunction.exe吗?
  • 创建一个包含您要执行的所有myFunction.exe 的批处理文件,并使用Process 运行该批处理文件。
  • 因为它有参数,所以无论如何它都会打开一个 cmd 窗口。问题是我需要它来运行带有参数 1-52 的函数,并且我不希望 52 cmd 窗口在它打开时打开这样做。

标签: c# cmd process


【解决方案1】:

第一个using 块创建一个包含所有要执行的命令的批处理文件。第二个using 块执行批处理文件。

using (StreamWriter sw = new StreamWriter("myFunctions.cmd"))
{
    for (int j = 0; j < 25; j++)
    {
        for (int i = 0; i < Device_Numbers.Count; i++)
        {
            sw.WriteLine("myFunction.exe " + i + " = " + j);
        }
    }
}

using (Process process = new Process())
{
    process.StartInfo.FileName = "cmd.exe";
    process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    process.StartInfo.Arguments = "/C myFunctions.cmd";
    process.Start();
    process.WaitForExit();
}

【讨论】:

  • @Aaron Lind - 这回答了你的问题吗?
猜你喜欢
  • 2013-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-22
  • 1970-01-01
相关资源
最近更新 更多