2011-02-18 76 views
2

嘿人!我正在使用名爲MineMe的小工具,它用於處理Minecraft服務器。啓動批處理流時C#凍結

所以我做了一個文件流,應該流的start_base.cmd(啓動服務器的文件)的輸出。哪裏出了問題,是與我的形式凍結窗口,直到我殺進程(java.exe的 - 由start_base.cmd冉)

這裏是我的代碼:

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(); 
     } 

有什麼不對嗎? :)請幫我..

回答

3

在您的UI線程啓動另一個線程來處理while循環:

Thread t = new Thread(new ThreadStart(DoWork)); 
t.Start(); 


public void DoWork() 
{ 
    // work to be done on another thread 
} 
2

問題是你的while循環。您需要在單獨的線程(即不是您的UI線程)上執行此操作。

如果您是通過單擊按鈕(或其他某個UI控件)調用上述代碼,則應該使用BackgroundWorker線程或線程池中的線程(或者甚至只是普通的vanilla線程)執行此任務。

+0

對不起:)我不認爲我明白你 - 你能請編輯代碼? :D – 2011-02-18 12:40:26

+0

@Frederik:`tzup`的答案顯示了「普通香草線程」的方法,它可以很好地滿足您的需求。這裏有一個鏈接展示瞭如何使用`ThreadPool`線程:http://msdn.microsoft.com/en-us/library/3dasc8as(v=vs.80).aspx#Y440 – MusiGenesis 2011-02-18 14:29:11