Android Question Problem with Sleep(0)

RB Smissaert

Well-Known Member
Licensed User
Longtime User
I have this simple Sub for setting the required menu group:

B4X:
Sub ShowMenuGroup(iMenuGroup As Int)

    Dim i As Int
    
    For i = 1 To 5
        ActionBar.Menu.SetGroupVisible(i, i = iMenuGroup)
    Next
    
    iCurrentMenuGroup = iMenuGroup
    
    If iMenuGroup = 5 Then
        Sleep(0) 'this is needed, otherwise buttons remain visible!
        Dim bVisible As Boolean = General.iCurrentPanelType <> Enums.ePanelType.ShowWebview
        ActionBar.Menu.GetItem(Enums.eMenuButtonType.PreviousPanel).Visible = bVisible
        ActionBar.Menu.GetItem(Enums.eMenuButtonType.NextPanel).Visible = bVisible
    End If

End Sub

I need the Sleep(0) as otherwise the buttons won't hide.
I used to have the line: iCurrentMenuGroup = iMenuGroup after the If code block, but found out that it won't run
with the Sleep(0) in place. Luckily there is no problem put that line before the If code block and then all is well.

Is this normal behaviour?
What if for some reason I needed to have that line after the If code block?

RBS
 

agraham

Expert
Licensed User
Longtime User
Is this normal behaviour?
Yes. Code execution needs to get back to the apps message loop before the buttons can be redrawn in their new state. The Sleep should be outside the If otherwise it only runs when the If is satisfied. However the Sub is so small and should run so quickly before returning that it is not obvious why the Sleep is needed at all without seeing the full context of its use.

I used to have the line: iCurrentMenuGroup = iMenuGroup after the If code block, but found out that it won't run
Are you really sure of that? I can see no reason why it shouldn't.
 
Upvote 0

RB Smissaert

Well-Known Member
Licensed User
Longtime User
Yes. Code execution needs to get back to the apps message loop before the buttons can be redrawn in their new state. The Sleep should be outside the If otherwise it only runs when the If is satisfied. However the Sub is so small and should run so quickly before returning that it is not obvious why the Sleep is needed at all without seeing the full context of its use.

Are you really sure of that? I can see no reason why it shouldn't.

If iMenuGroup <> 5 then I don't need to alter the buttons, so I don't need the Sleep.
Yes, I am sure that if that line is after the If block it won't run, that is if iMenuGroup is 5.

To me it seems the need for these Sleep(0) statements is bit of a problem in B4A as you
never can be sure where they are needed and it can cause bugs that are difficult to trace.

RBS
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
Upvote 0
Top