未处理TCP的Timeoutexception

时间:2012-12-13 11:58:33

标签: vb.net tcp timeoutexception

我从网站上获取此代码,因为VS 2010不支持TCP连接的超时:

Private Function ConnectWithTimeout() As Boolean
    Dim ar As IAsyncResult = TCPClient.BeginConnect(IPAddress, TCPPort, Nothing, Nothing)
    Dim wh As System.Threading.WaitHandle = ar.AsyncWaitHandle

    Try
        If Not ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(2), False) Then
            TCPClient.Close()
            TCPClient = New System.Net.Sockets.TcpClient
            Throw New TimeoutException()
        End If
    Catch ex As Exception
        ThrowError("Timeout on connecting to " & IPAddress & " at port " & TCPPort & ".")
        Return False
    Finally
        wh.Close()
    End Try

    Return True
End Function

它工作正常,但每次都在调试输出上给我这个:

“在'

中发生'System.TimeoutException'类型的第一次机会异常

即使我抓住了所有例外情况。有没有办法摆脱处理这个异常消息?

我试过这个:

    Dim connectDone As New System.Threading.AutoResetEvent(False)
    TCPClient.BeginConnect(IPAddress, TCPPort, New AsyncCallback(Sub(ar As IAsyncResult)
                                                                     TCPClient.EndConnect(ar)
                                                                     connectDone.Set()
                                                                 End Sub), TCPClient)
    'client.BeginConnect("127.0.0.1", 80, new AsyncCallback(delegate( IAsyncResult ar ) { client.EndConnect( ar );  connectDone.Set(); }), client);

    If Not connectDone.WaitOne(2000) Then
        Debug.WriteLine("TIMEOUT")
        Return False
    End If

    Return True

但是它在beginconnect行上给了我InvalidOperationException: 在同一个Socket上正在进行另一个异步操作时,无法调用BeginConnect。

1 个答案:

答案 0 :(得分:-1)

Private Function ConnectWithTimeout() As Boolean
    Dim ar As IAsyncResult 
    Dim wh As System.Threading.WaitHandle  

    Try
          ar = TCPClient.BeginConnect(IPAddress, TCPPort, Nothing, Nothing)
          wh = ar.AsyncWaitHandle
    Cath ex as Exception
          'Code to catch exception
    End Try

    Try
        If Not ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(2), False) Then
            TCPClient.Close()
            TCPClient = New System.Net.Sockets.TcpClient
            Throw New TimeoutException()
    End If
    Catch ex As Exception
        ThrowError("Timeout on connecting to " & IPAddress & " at port " & TCPPort & ".")
        Return False
    Finally
        wh.Close()
    End Try

    Return True
End Function