我在这里遇到了一种奇怪的行为。控件永远不会从do-while循环中出现。调试时,我发现变量间隔的值在某些循环中减少,而不是增加!我漏掉了一些显而易见的东西,但我想不出来。
static void Main(string[] args)
{
int interval = 0;
DateTime startTime = DateTime.Now;
//Task1(); //Task1 can take 4-8 seconds to complete
do
{
Thread.Sleep(100);
interval = (DateTime.Now - startTime).Milliseconds;
} while (interval < 10000); //wait for at-least ten seconds from program start, before executing task2
//Task2();
}发布于 2017-08-30 12:05:54
您的问题是度量TimeSpan的毫秒部分。您必须使用TotalMilliseconds而不是Milliseconds
do
{
Thread.Sleep(100);
interval = (DateTime.Now - startTime).TotalMilliseconds;
} while (interval < 10000); //wait for at-least ten seconds from program start, before executing task2发布于 2017-08-30 12:05:35
不要使用DateTime来测量时间间隔。
使用Stopwatch类,它正是为此目的而设计的
var clock = new Stopwatch();
clock.Start();
do
{
// do something
}
while (clock.ElapsedMilliseconds < 10000)
clock.Stop();注意:当然,您可以使用DateTime来测量时间,但是如果您需要的精度小于秒,那么Stopwatch是适合这项工作的工具。
而且Stopwatch有更多的可读性和易于使用的测量时间的方法。
在您的特殊情况下:“在执行task2之前,从程序开始至少等待10秒钟”,您可以使用异步方法。
var task1 = StartTask1();
await Task.Delay(10000); // next line will be executed approximately after 10 s
var task2 = StartTask2();发布于 2017-08-30 12:12:25
对于TimeSpan,如果您想知道已经过去的总时间,就必须使用Total属性。前面没有Total的所有属性都只显示当前已过的时间。
例如:一个方法运行1分7秒。
Console.WriteLine(ts.Seconds);输出:
7
为什么会这样呢?因为现在只有60秒,ts.Seconds会从0增加到59。
把这个和
Console.WriteLine(ts.TotalSeconds),输出:
67
现在我们有了已经过去的总秒数,在这个例子中是67秒。
https://stackoverflow.com/questions/45959959
复制相似问题