How do you expect a bool to stay true?

Asked

Viewed 127 times

1

I have this method async currently waiting for a time declared by me. The program first restarts the boolean result and then send commands to a serial that after a certain time returns in my program the results in that same boolean.

But it’s obviously bad practice I need to set the time "hard coded" why for some reason can get the answer faster than expected, or even slower. Below a sample of how is the code:

public async Task StartNewTest(TestType test)
{
   double time = 0;
   switch(test)
   {
     case TestType.Alerts:
        time = 20000;
        AlertOK = false;
        SendSerial("A");
     case TestType.Lights:
        time = 18000;
        LightsOK = false;
        SendSerial("L");
   }
   await Task.Delay(TimeSpan.FromMilliseconds(time));
}

So it’s functional. But I’d like to stop using this form this time, waiting for Boolean AlertOK stick around true for example.

Like it was (just an idea). await AlertOK == true

1 answer

2


I don’t know how the method called yours is implemented StartNewTest, but you can start this method in another thread:

await Task.Factory.StartNew(async () =>
{           
    await StartNewText(TestType);
});

This allows us to use a while without halting the UI:

case TestType.Lights:
{
    LightsOK = false;
    SendSerial("L");
    while(AlertOK == false) {}
    break;
}

This way you can remove the await Task.Delay(TimeSpan.FromMilliseconds(time)) and your method will stay in there until the variable AlertOK become true.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.