c#:
public bool Test()
{
using (var tcp = new TcpClient())
{
var c = tcp.BeginConnect(IPAddress.Parse("8.8.8.8"), 8080, null, null);
var success = c.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1));
if (!success)
{
Console.WriteLine("Before cleanup");
tcp.Close();
tcp.EndConnect(c);
Console.WriteLine("After cleanup");
throw new Exception("Failed to connect.");
}
}
return true;
}
vbnet:
Public Function Test() As Boolean
Using tcp As Object = New TcpClient()
Dim c As Object = tcp.BeginConnect(IPAddress.Parse("8.8.8.8"), 8080, Nothing, Nothing)
Dim success As Object = c.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1))
If Not success Then
Console.WriteLine("Before cleanup")
tcp.Close()
tcp.EndConnect(c)
Console.WriteLine("After cleanup")
Throw New Exception("Failed to connect.")
End If
End Using
Return True
End Function
====
調整用法:
Public Function Test() As Boolean
Using tcp As Object = New TcpClient()
Dim c As Object = tcp.BeginConnect(IPAddress.Parse("192.168.1.78"), 1435, Nothing, Nothing)
Dim success As Object = c.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1))
If Not success Then
tcp.Close()
Return False
End If
End Using
Return True
End Function
沒有留言:
張貼留言