未处理TCP的Timeoutexception

问题描述 投票:0回答:1

我从网站上获取此代码,因为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。

vb.net tcp timeoutexception
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
© www.soinside.com 2019 - 2024. All rights reserved.