【问题标题】:Program1 doesn't run Program2 properlyProgram1 不能正确运行 Program2
【发布时间】:2021-04-22 19:50:49
【问题描述】:

我有两个简单的控制台应用程序。 Program1 调用 Program2 将 500 个文件简单移动到另一个文件夹。

Program1.exe:

    static void Main(string[] args)
    {
        System.Diagnostics.Process proc = new System.Diagnostics.Process();
        proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
        proc.EnableRaisingEvents = false;
        proc.StartInfo.RedirectStandardOutput = true;
        proc.StartInfo.RedirectStandardInput = true;
        proc.StartInfo.UseShellExecute = false;
        proc.StartInfo.FileName = @"D:\Program2.exe";
        proc.Start();
        proc.WaitForExit();
        proc.Close();
    }

Program2.exe:

    static void Main(string[] args)
    {
            string srcDic= @"D:\docs";
            var DesDic= @"D:\docs2";

            var pdf_files = Directory.GetFiles(srcDic, "*.pdf", SearchOption.TopDirectoryOnly);
            foreach (var pdf_file in pdf_files)
            {
                var fileName = new DirectoryInfo(pdf_file).Name;
                File.Move(pdf_file, DesDic + "\\" + fileName);
                Console.WriteLine("Moving " + pdf_file);
            }

            Console.WriteLine("----- All files moved!");
    }

问题: 当我运行 Program1.exe 来运行 Program2 时,大多数情况下 Program2 会被冻结并且不会移动所有文件。我必须手动关闭它。

注意:

  • 当我在没有 Program1 的情况下运行 Program2.exe 时,它​​运行良好并且可以移动所有文件。
  • 我没有防病毒软件,我什至关闭了 Windows Defender 防火墙
  • 这段代码是一个大软件的一部分,我不想直接在Program1中写移动代码

【问题讨论】:

  • 如果你要重定向 StandardOutput 你需要read it before exiting
  • 设置 proc.StartInfo.RedirectStandardOutput = false 再试一次。
  • @DourHighArch 我有 StandardOutput.ReadToEnd() 但它是在 .WaitForExit(); 之后。我把它移到了之前。我想它解决了这个问题,但我不确定这是否再也不会发生。
  • 如果您不打算写入 StandardInput 或从 StandardOutput 读取,则不应重定向它们。

标签: c# .net cmd


【解决方案1】:

您是否尝试过降低 APP 2 测试运行的文件数量?将 Docs 目录中的文件数量减少到 20 个,看看它是否仍然冻结。也可能是时间问题。 粘贴一个 Thread.Sleep();经过这一步只是为了看看,我不会在最终产品中使用它。 proc.StartInfo.UseShellExecute = false;

【讨论】:

    猜你喜欢
    • 2023-04-11
    • 2012-04-05
    • 1970-01-01
    • 2011-10-30
    • 1970-01-01
    • 1970-01-01
    • 2011-02-20
    • 2019-06-01
    • 1970-01-01
    相关资源
    最近更新 更多