我需要一种方法,每隔15秒使用C#定期检查一些请求的状态。我将使用Xamarin.Forms,如果我不必编写任何特定于平台的代码,那就太好了。
我需要每15秒检查一次状态两分钟。如果请求被拒绝或被接受,我需要检查停止并运行一些其他代码。这样做的最佳方法是什么?
答案 0 :(得分:0)
基本上,创建计时器可以做到这一点。这是一个关于如何每15秒检查一次请求2分钟的示例。
int twoMinutesCounter = 1; // the value that will reach 120 seconds; 2 minutes = 120 seconds
int fifteenSeconds = 15; // obvious
int secondsElapsed = 1;
// create a timer that ticks every 1 second
DispatcherTimer theTimer = new Timer();
theTimer.Interval = new Timespand(0,0,0,1); // days, hours, minutes, seconds
// the elapse event. here put your request checking
theTimer.Elapsed += (_, __) =>
{
// if its 2 minutes then stop the timer
if (twoMinutesCounter >= 120)
{
// stop the timer to stop checking
theTimer.Stop();
}
// check if its 15 seconds
if (secondsElapsed >= fifteenSeconds)
{
// here, request to check the status
// do the checking
// reset the seconds elapse to check again for 15 seconds
secondsElapsed = 1;
}
secondsElapsed++; // increase seconds elapse
twoMinutesCounter++; // increase the two minutes counter every seconds
}
// start the timer
theTimer.Start();