简体   繁体   English

无法从C#执行大型批处理文件

[英]Trouble executing large batch file from C#

I'm executing a batch file from my C# application using the System.Diagnostics classes, updating my GUI with the output along the way, but as soon as my batch file is in excess of a certain number of lines, the process just hangs. 我正在使用System.Diagnostics类从我的C#应用​​程序执行批处理文件,在整个过程中使用输出更新我的GUI,但是只要我的批处理文件超过一定数量的行,该过程就会挂起。 The exact amount of lines seems to vary, but I have been able to reproduce it with a simple batch file that prints "Hello Kitty" 316 times: 确切的线条数量似乎有所不同,但我已经能够使用一个简单的批处理文件重现它,打印出“Hello Kitty”316次:

@echo off
echo Hello Kitty
echo Hello Kitty

etc. 等等

If I remove the 316th line, the batch file executes fine and the forms application behaves as expected, but any more lines causes the process to suspend indefinitely, not producing even one of the first 300 hello kitties. 如果我删除第316行,批处理文件执行正常,表单应用程序按预期运行,但是更多行导致进程无限期挂起,甚至不生成前300个hello kitty中的一个。

Here is my code for executing the batch file: 这是我执行批处理文件的代码:

process = new System.Diagnostics.Process();
process.StartInfo.FileName = batchName;
process.StartInfo.Arguments = " < nul";
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.UseShellExecute = false;
process.Start();

with these declared elsewhere: 这些在其他地方宣布:

protected Process process;
protected StreamReader output;

My main form does something like this (simplified a little): 我的主要表单做了这样的事情(简化了一点):

string output;

while (!proc.Process.HasExited)
{
    proc.Process.WaitForExit(200);

    if (proc.Process.HasExited)
    {
        output = proc.Output.ReadToEnd();
        rtbStatus.AppendText(output);
    }

    Application.DoEvents();
}

I don't understand why it does this, and no examples that I find on the net make any mention of a size limit on batch files. 我不明白为什么会这样做,我在网上找到的例子都没有提到批处理文件的大小限制。 Please advise. 请指教。

You need to read the output continuously - you cannot wait to the end. 你需要不断读取输出 - 你不能等到最后。

Output will be buffered, so a small amount (usually about 4KB) can be written before the process hangs. 输出将被缓冲,因此在进程挂起之前可以写入少量(通常约4KB)。

The alternative is to direct the output to a file then read the file. 另一种方法是将输出定向到文件然后读取文件。

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

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