大家好我创建了一个小应用程序,用命令执行“命令提示符”到目前为止我创建了一个带线程休眠的简单方法
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然后中止
答案 0 :(得分: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();
}
答案 1 :(得分:0)
您可以将WaitHandle.WaitOne(TimeSpan)用于此目的。