I try to test TCP connection with the following code.
System.Threading.Thread t = new System.Threading.Thread(() =>
{
using (TcpClient client =
There is no direct way to achieve it, but one way to do it can be to have a seperate method which would test the connection.
static bool TestConnection(string ipAddress, int Port, TimeSpan waitTimeSpan)
{
using (TcpClient tcpClient = new TcpClient())
{
IAsyncResult result = tcpClient.BeginConnect(ipAddress, Port, null, null);
WaitHandle timeoutHandler = result.AsyncWaitHandle;
try
{
if (!result.AsyncWaitHandle.WaitOne(waitTimeSpan, false))
{
tcpClient.Close();
return false;
}
tcpClient.EndConnect(result);
}
catch (Exception ex)
{
return false;
}
finally
{
timeoutHandler.Close();
}
return true;
}
}
This method would use a WaitHandle that would wait for the specified time period to get the connection established, if it gets connected in time, it would close the connection and return true, else, it would timeout and return false.