C# freeze while starting batch stream
Hey people! I am working with my little tool called MineMe, and it is used to handle Minecraft servers.
So i made a file stream, that should stream the output of the start_base.cmd (the file that starts the server). What goes wrong, is tha开发者_C百科t the window with my form freezes, until i kill the process (java.exe - Ran by start_base.cmd)
Here is my code:
ProcessStartInfo processInfo = new System.Diagnostics.ProcessStartInfo("CMD");
processInfo.WindowStyle = ProcessWindowStyle.Normal;
processInfo.RedirectStandardOutput = true;
processInfo.RedirectStandardInput = true;
processInfo.RedirectStandardError = true;
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
Process p = new Process();
p.StartInfo = processInfo;
p.Start();
TextWriter tw = p.StandardInput;
tw.Flush();
tw.WriteLine("start_base.cmd");
tw.Close();
TextReader tr = p.StandardOutput;
string output = tr.ReadLine();
while (output != null)
{
this.lg_log.Items.Add(output); // add the output string to a list box
output = tr.ReadLine();
}
What's wrong here? :) Please help me ..
On your UI thread start another thread to process the while loop:
Thread t = new Thread(new ThreadStart(DoWork));
t.Start();
public void DoWork()
{
// work to be done on another thread
}
The problem is your while
loop. You need to do this on a separate thread (i.e. not your UI thread).
If you're calling the above code from a button click (or some other UI control), you should instead use a BackgroundWorker thread or a thread from the thread pool (or even just a plain vanilla Thread) for this task.
精彩评论