大家好,我创建了一个小应用程序来使用命令执行“command prompt”到目前为止,我创建了一个简单的线程休眠方法

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秒,然后中止。

最佳答案

对时间跨度使用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();
    }

09-26 06:40