B4J Question Wait For doesn't return/resume if exception is thrown

miker2069

Active Member
Licensed User
Longtime User
I was experiencing an issue with using wait for on a simple socket based connection. For example:
B4X:
    Dim sock As Socket
    Dim Successful As Boolean
    '<----this IP doesn't exist or isn't listening on specified port so connect exception will be thrown
    Dim txtip As String = "10.0.0.23"
 
    sock.Initialize("sock")
    Log("Connect attempt")
    sock.Connect(txtip, 51042, 10000)
    'connect to nodemcu
    Wait For (Successful) sock_Connected (Successful As Boolean)
    Log("Returned from connection attempt")

I noticed that if I "wait for" sock_Connected and there's an exception thrown, the wait for never resumes. Now if instead use an independent event handler like so...

B4X:
Sub sock_Connected (Successful As Boolean)

    Log("Connected Status:" & Successful)
    If Successful = False Then
        Log(LastException) 
    else
        Log("Successfully connected...")
    End If
End Sub

I can check the Successful result and if false check for the last exception. I was thinking I should be able to do all that after the wait for. So I am assuming if an exception occurs while waiting for an event, that wait for will sit there forever. Is this correct behavior? I thought an example of wait for in B4A with SQL that seems to demonstrate that it would gracefully return and possibly check the LastException.

To add to the discussion, I tried putting try/catch blocks around the wait for line and that didn't help - only way it works is to use a discrete sock_connected event handler routine.

For now I can re-arrange my code to work like I need it to - just looking for some clarity.

thanks!
 

miker2069

Active Member
Licensed User
Longtime User
Looks like I had an error ( couldn't delete thread so I will post this addendum):

I changed the line:

B4X:
  Wait For (Successful) sock_Connected (Successful As Boolean)

to:

B4X:
  Wait For sock_Connected (Successful As Boolean)

And it works as expected - I can check the value of Successful and then dump lastexception. I was under the impression you had to parameterize the event args. Anyway sorry for the confusion.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
The parameter inside the optional first parenthesis is the sender filter. It must match the Sender value for the event to be intercepted.

In your case the correct signature is:
B4X:
Wait For (sock) sock_Connected (Successful As Boolean)

As a general rule it is better to use the sender filter when possible. It allows multiple resumable subs to wait for event with the same signature.
 
Upvote 0
Top