开发者

C# Process + Backgroundworker & timer error

I have some code that spawns a process, the file being executed is a Java application and my intent is to read the output from it.

The problem is that when I call Start, I am unable to read the output stream after that point. If I test and call Console.Beep after calling Start then the beep will occur - so it is obviously executing these lines.

Control.CheckForIllegalCrossThreadCalls = false; 

Process java = new Process();
java.StartInfo.FileName = "java";
java.StartInfo.Arguments = "-Xms1024M -Xmx1024M -jar craftbukkit-0.0.1-SNAPSHOT.jar nog开发者_JAVA技巧ui";
java.StartInfo.RedirectStandardOutput = true;
java.StartInfo.UseShellExecute = false;
java.Start();

System.Console.Beep();
System.Console.Write("hejsan");
StreamReader Reader = java.StandardOutput;

txtLog.Text = Convert.ToString(System.Console.Read());
broadcast(Convert.ToString(System.Console.Read()), "[Server]", false);

Why can't I read from the output stream?


Take a look at this Microsoft reference of StandardOutput.

Basically, you need to call WaitForExit and attempt to read the stream after that. It's a blocking call, so unless you do some funky stuff with it and asynchronism, this is fairly straight forward:

if (java.Start())
{
    java.WaitForExit();
    var reader = java.StandardOutput;
    output = reader.ReadToEnd();
}

It's worth mentioning here that the Start method returns a boolean value indicating whether or not the process was actually started - this helps us decide what to do, and whether or not we can do it.

On another note, I can't help but notice that you don't actually try to read from the output stream, you simply declare a variable with a reference to it; in order to utilise it, then you will need to call the methods exposed by the class, such as ReadToEnd - I have added usage to the example above.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜