Home > front end >  Why can't I use Timer to perform a declaration of a variable
Why can't I use Timer to perform a declaration of a variable

Time:02-18

Since I need to have the latest data in the database through non-stop repeated declarations. I want to achieve my goal by setting timer. My current idea is to use this way, but this does not work.

Can someone give me advice?

var timer = new PeriodicTimer(TimeSpan.FromSeconds(10));

while (await timer.WaitForNextTickAsync())
{
    double H = Model.LastOrDefault().Ax;
    double V = Model.LastOrDefault().Ay;
}

CodePudding user response:

I'm assuming that you wish to use your variables H and V in code that is not in your while loop.

In the code:

var timer = new PeriodicTimer(TimeSpan.FromSeconds(10));

while (await timer.WaitForNextTickAsync())
{
    double H = Model.LastOrDefault().Ax;
    double V = Model.LastOrDefault().Ay;
}

H and V are only in scope within the while loop and as such can only be used within it. In other words they are local to the while loop and not outside of it e.g.:

while (await timer.WaitForNextTickAsync())
{
    double H = Model.LastOrDefault().Ax;
    double V = Model.LastOrDefault().Ay;
    double Sum = H V; // okay
}
double Sub = H-V;//Not possible as H & V are out of scope being local to the while loop

If you wish to use H and V elsewhere then they must be declared in such as place as that they are still in scope (accessible) where you wish to use them.

var timer = new PeriodicTimer(TimeSpan.FromSeconds(10));
double H=0.0;
double V=0.0;
while (await timer.WaitForNextTickAsync())
{
    H = Model.LastOrDefault().Ax;
    V = Model.LastOrDefault().Ay;
        double Sum = H V; // okay
}
double Sub = H-V;//okay as well
  • Related