The IAsyncResult object was not returned from the corresponding asynchronous method on this class

1k Views Asked by At

I have software that connects over TCP/IP to 4 differents devices (Weigher and 3 barcode scanners). About once or twice a day, I get an error that make the software crash:

System.ArgumentException: The IAsyncResult object was not returned from the corresponding asynchronous method on this class. Parameter name: asyncResult at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)

I really don't understand why and I can't figure it out. Here the code to connect to device

client = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
        port = RemotePort
        ipHostInfo = Dns.Resolve(RemoteHostName)
        ipAddress = ipHostInfo.AddressList(0)
        Dim remoteEP As New IPEndPoint(ipAddress, port)
        client.Connect(remoteEP)
        If client.Connected Then
            Dim state As New StateObject
            state.workSocket = client
            currentAsyncResult = client.BeginReceive(state.buffer, 0, state.BufferSize, 0, AddressOf sockDataArrival, state)
            RaiseEvent onConnect()
        End If

The StateObject class:

Public Class StateObject
   Public workSocket As Socket = Nothing
   Public BufferSize As Integer = 256
   Public buffer(BufferSize) As Byte
   Public sb As New StringBuilder()
End Class

And the dataArrival event:

 Private Sub sockDataArrival(ByVal ar As IAsyncResult)
    Dim state As StateObject = CType(ar.AsyncState, StateObject)
    Dim client As Socket = state.workSocket
    Dim bytesRead As Integer

    If ar IsNot currentAsyncResult Then
        Exit Sub
    End If

    Try
        bytesRead = client.EndReceive(ar)
    Catch
        Exit Sub
    End Try

    Try
        Dim Data() As Byte = state.buffer
        If bytesRead = 0 Then
            client.Shutdown(SocketShutdown.Both)
            client.Close()
            RaiseEvent onDisconnect()
            Exit Sub
        End If
        ReDim state.buffer(state.BufferSize)

        currentAsyncResult = client.BeginReceive(state.buffer, 0, state.BufferSize, 0, New AsyncCallback(AddressOf sockDataArrival), state)
        RaiseEvent onDataArrival(Data, bytesRead)
    Catch
        RaiseEvent onError(Err.Description)
        Exit Sub
    End Try
End Sub

Is there anything I'm doing wrong here? How can I fix this error? thanks a lot for your time and help

0

There are 0 best solutions below