0

由于 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。

4

1 回答 1

-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
于 2013-11-01T21:17:51.033 回答