如何检查特定时间是否已过

本文关键字:定时间 是否 何检查 检查 | 更新日期: 2023-09-27 18:33:36

我正在启动我的操作,我的命令行应用程序得到的参数之一是Number表示我的操作需要运行多少时间。

int duration = int.Parse(args[0]) // run my operation for this time in minutes

这是我尝试过的(不起作用):

...
DateTime start = DateTime.Now;
// check whether this time in minutes passed
if (start.Minute > duration )
    break;

如何检查特定时间是否已过

编辑:使用UtcNow

    void DoWork(int durationInMinutes)
    {
        DateTime startTime = DateTime.UtcNow;
        TimeSpan breakDuration = TimeSpan.FromMinutes(durationInMinutes);
        // option 1
        while (DateTime.UtcNow - startTime < breakDuration)
        {
            // do some work
        }
        // option 2
        while (true)
        {
            // do some work
            if (DateTime.UtcNow - startTime > breakDuration)
                break;
        }
    }

为此,您可以通过定义来使用StopWatch

StopWatch watch = new StopWatch();
watch.Start();

以及您的代码完成运行

写入的位置
watch.Stop();

通过使用 stopwach,您可以详细查看应用程序的运行时间。当然,如果我理解你是正确的。