Android Code Snippet [B4X] Wait for multiple tasks to complete

A pattern such as this one can be used when you want to run multiple resumable subs concurrently and wait for all of them to complete before continuing:
    Dim status(1) As Int
    Do While status(0) < 3
    Log("all tasks completed. Continue with your next task...")

Private Sub Test1 (Status() As Int)
    Sleep(Rnd(1, 1000))
    Log("Test1 completed")
    Status(0) = Status(0) + 1
End Sub

Private Sub Test2 (Status() As Int)
    Sleep(Rnd(1, 1000))
    Log("Test2 completed")
    Status(0) = Status(0) + 1
End Sub

Private Sub Test3 (Status() As Int)
    Sleep(Rnd(1, 1000))
    Log("Test3 completed")
    Status(0) = Status(0) + 1
End Sub
For example, you might want to download multiple resources and process them together.
Note that it doesn't need to be three different subs. You can call the same sub multiple times. Just make sure to set the counter (3 in the example) to match the number of calls.
And don't worry about this loop. It is not a busy loop. It is similar to using a timer to poll something.


Licensed User
Longtime User
It's probably one of those machine code instructions that overlaps with the instructions before and after it, and thus takes no additional cycles to execute.

Light travels 0.3 nanometers in that specified time, which is about the diameter of one silicon atom, which would represent the gap between the two instructions.
I, on the other hand, hope it was a joke, to indicate in any case an infinitesimal time, absolutely irrelevant.


Well-Known Member
Licensed User
Longtime User
This whole debate about "status" seems to confirm my objection about "hack" and "language-level solution"


B4X founder
Staff member
Licensed User
Longtime User
Editing this post a bit:
The Wait For feature is one of the most important features of B4X programming language. Under the hood, it is one of the most complicated features in B4X, and still the API itself is quite clean and elegant.
Making it more complicated in order to solve an edge case is unreasonable.
As you can see in this simple code, we can already do it with a small loop.

And remember that in a real app, the logic can be more complicated than simply waiting for X tasks to complete. The suggested code is only a guidance for developers which can take it and modify it to meet their app requirements.
Last edited: