2012-10-05 60 views
1

大家好我創建了一個小的應用程序來執行「命令提示符」的命令到目前爲止,我創建的線程睡眠的簡單方法執行shell C#

public static string Executecmd(string command, int sleepSec) { 
    try { 
     string result = null; 
     System.Threading.Thread objThread = new System.Threading.Thread(delegate() { 
      result = ExecuteCommandSync(command); 
     }); 
     objThread.IsBackground = true; 
     objThread.Start(); 
     while (objThread.IsAlive == true) { 
      System.Threading.Thread.Sleep(sleepSec * 1000); 
      objThread.Abort(); 
     } 
     return result; 
    } 
    catch (Exception x) { 
     Console.WriteLine(x.Message + "\n" + x); 
     return null; 
    } 
} 

它工作正常,但即使命令執行完成它保持睡眠,直到線程睡眠完成,所以我的問題是如何創建一個方法,將超出它,睡5秒,如果它完成它停止其他等待5秒,然後中止

回答

2

使用Thread.Join與時間跨度。

System.Threading.Thread objThread = new System.Threading.Thread(delegate() { 
     result = ExecuteCommandSync(command); 
    }); 
    objThread.IsBackground = true; 
    objThread.Start(); 

    //Waits here for "sleepSec" seconds or until the thread finishes, whichever is shorter. 
    if(objThread.Join(new TimeSpan.FromSeconds(sleepSec)) == false) 
    { 
     //Only executes this code of the thread did not finish before the timeout. 
     objThread.Abort(); 
    } 
+0

非常感謝你的魅力;>謝謝B. –