1

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

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

4

2 回答 2

3

使用具有时间跨度的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();
    }
于 2012-10-05T21:08:34.977 回答
0

您可以为此目的使用WaitHandle.WaitOne(TimeSpan) 。

于 2012-10-05T21:06:25.833 回答