Android Question How should I wait for a status flag to be set or not

Patrick Clark

Active Member
Licensed User
I have some code where I need to wait for an event to be fired but must timeout if it takes too long.

The way I am doing it at the moment is below. I set an Acknowledged flag to 0 and then loop until it is not 0.

It will be set to 1 in the event I am waiting for or -1 if the timer ticks. (the timer is disabled in the event so it doesn't fire after the event has happened)

Acknowledged and bkrtmr are both Public and declared in Process_Globals

This all seems to make sense but often I get the situation where the timer doesn't tick and I wait forever.

Is there a better way of doing this???

B4X:
'in the start broker sub
'
Acknowledged = 0
brktmr.Initialize("brktmr", 2000)
brktmr.Enabled = True

Do While Acknowledged = 0
    Sleep(50)
Loop

'at this point Acknowledged should be:
'    1 (from the client.connected event) or
'    -1 from the brktmr_Tick event


'the Timer tick
Public Sub brktmr_Tick
    brktmr.Enabled = False
    Acknowledged = -1
End Sub

'The event
Public Sub Event
brktmr.Enabled = False
Acknowledged = 1
End Sub
 

JohnC

Expert
Licensed User
Longtime User
I would do it without a timer:

B4X:
    Dim TimeoutTime As Long
  
    TimeoutTime = DateTime.Now + (DateTime.TicksPerSecond * 2)
  
    Do While Acknowledged = 0 And DateTime.Now < TimeoutTime
        Sleep(0)
    Loop

    'if Acknowledged = 0 then it timed out
 
Upvote 0

Patrick Clark

Active Member
Licensed User

@JohnC That is GENIUS, Thank you as so much more elegant
 
Upvote 0

Patrick Clark

Active Member
Licensed User
1. Make sure not to initialize the timer multiple times. Bad things will happen.
2. Check the logs. The sleep will not be resumed if the activity is destroyed. You will see a message in the logs.

Thanks @Erel , JohnC has given me a fabulous solution to my problem but a couple of questions about the timers that your reply brings up.

1. Are you saying Initialize once and the just use .Interval if I want to change the length of the timer?

2. If I initialize a timer for 1000ms and 500ms later I disable it. Then I Enable it again will it start to count again for a full 1000ms or only the remaining 500ms


Thanks
 
Upvote 0

JohnC

Expert
Licensed User
Longtime User
1. Are you saying Initialize once and the just use .Interval if I want to change the length of the timer?
Yes
2. If I initialize a timer for 1000ms and 500ms later I disable it. Then I Enable it again will it start to count again for a full 1000ms or only the remaining 500ms
Full 1000ms
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…