我如何创建一个函数,如果一个计数器保持5秒钟不变,那会发生什么?据我所知,我必须为旧的计数器值分配一个名称,然后再进行比较。这是正确的吗?
我的代码包含超时
if (x1 && y1 && z1)
{
txtAngle.Text = "";
txtDisplay.Text = "Number of times: " + counter + "\n" + "Go back to start position and repeat the exercise for " + databaseValue + " times";
txtAgain.Text = "Go back to starting position.";
txtAgain1.Text = "";
counter++;
// assign the old counter value as previous counter
if (counter == previousCounter) // If the counter never increase for 5 seconds
{
timeout.Tick += timeout_TickAsync;
timeout.Interval = TimeSpan.FromSeconds(5);
timeout.Start();
}
timeangle1.Stop();
}
超时功能
private void timeout_TickAsync(object sender, object e)
{
// something happens.
txtClock.Text = "HELLO WORLD";
timeout.Stop();
}
此代码有一个错误,因为它不完整,Idk将从此处继续。有人,请帮助我。
答案 0 :(得分:0)
您可以使用异步方法来处理。
void aync Task UpdateCounterAsync(int newValue)
{
var oldValue = _counter;
_counter = newValue;
await Task.Delay(Timespan.FromSeconds(5));
if (_counter == oldValue)
{
// counter is still the same; do something
}
}
它将更新名为_counter
的成员变量,等待5秒钟,并检查延迟后可用的值是否仍然相同。
如果您想提高弹性,还可以跟踪Task.Delay()
返回的任务,并在每次进行新更新时将其取消。您将需要一个CancellationTokenSource
成员变量,例如_cancellationTokenSource
void aync Task UpdateCounterAsync(int newValue)
{
var oldValue = _counter;
_counter = newValue;
_cancellationSourceToken.Cancel();
_cancellationSourceToken = new CancellationSourceToken();
try
{
await Task.Delay(Timespan.FromSeconds(5), _cancellationSourceToken.Token);
if (_counter == oldValue)
{
// counter is still the same; do something
}
}
catch (TaskCancelledException)
{
// another update has been triggered while we were waiting.
// _counter has obviously changed then bail out
}
}