gpt4 book ai didi

c# - 超时执行shell c#

转载 作者:可可西里 更新时间:2023-11-01 11:58:34 25 4
gpt4 key购买 nike

大家好我已经创建了一个小应用程序来使用命令执行“命令提示符”到目前为止我创建了一个简单的线程 sleep 方法

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

它工作正常,但即使命令执行完成,它也会保持 sleep 状态,直到线程 sleep 完成,所以我的问题是如何创建一个方法来执行它并 sleep 5 秒,如果它完成它会停止,否则等待 5秒然后中止

最佳答案

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

关于c# - 超时执行shell c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12753955/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com