所以,这很容易解释,但我已经搜索过,找不到任何有相同问题的人.我的问题起源于一项长期的周期性任务,这项任务比我想要的更频繁.似乎每个Task.Delay()我创建并等待返回约为我在ms中指定的延迟的65%.
问题归结为下面的代码行返回大约640-660毫秒(根据visual studio.我在这行代码上设置了一个断点,然后是跟随它的那个,它说已经过了多久):
await Task.Delay(1000);
Run Code Online (Sandbox Code Playgroud)
在另外两台机器上,IDENTICAL代码库运行得很好.不仅是上面这个简单的陈述,还有周期性的任务.是否存在会影响Task.Delay(int millisecondsDelay)的设置?刻度类型,时钟速度,任何东西,系统时钟??? 我很茫然...
编辑:
在下面的代码片段中,EtMilliseconds是130-140ms,大约是相同的.上述预期持续时间的65%.从来没有任何东西(除了第一次进入while()是无关紧要的).
Long EtMilliseconds;
Stopwatch etWatch = new Stopwatch();
etWatch.Restart();
while (true)
{
EtMilliseconds = etWatch.ElapsedMilliseconds;
taskDelay = Task.Delay(200);
etWatch.Restart();
await taskDelay;
}
Run Code Online (Sandbox Code Playgroud)
编辑2:
以下代码导致EtMilliseconds再次为131ms左右.使用Thread.Sleep似乎没有效果......
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button_Click(object sender, RoutedEventArgs e)
{
long EtMilliseconds;
Stopwatch etWatch = new Stopwatch();
etWatch.Restart();
while (true)
{
EtMilliseconds = etWatch.ElapsedMilliseconds;
label.Content = EtMilliseconds.ToString();
etWatch.Restart();
Thread.Sleep(200);
}
}
}
Run Code Online (Sandbox Code Playgroud)
此代码段相同但使用Task.Delay(200).这个正确地更新了GUI标签(Thread.Sleep没有),它是131或140ms.总是...
public partial class MainWindow : …Run Code Online (Sandbox Code Playgroud)