I am looking for a way of setting up a tcpclient connection Asynchronously with timeout, I tried to find out the answers at How to set the timeout for a TcpClient?, but it's not working for me, I put the setup code into a task to avoid of blocking the main thread, timeout is needed cause the setup process may take more than 1 minutes to fail. Please help me to make timeout work.
using System;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
namespace test
{
class MainClass
{
public static void Main(string[] args)
{
Connect();
int seconds = 0;
while (true)
{
Console.WriteLine("time elapsed: " + seconds.ToString());
Thread.Sleep(1000);
seconds += 1;
}
}
public static async void Connect()
{
Tcp tcp = new Tcp();
await tcp.BeginConnect("apple.com", 3);
Console.WriteLine("connect end.");
}
}
class Tcp
{
public async Task BeginConnect(string ip, int port)
{
var client = new TcpClient();
Console.WriteLine("start connecting.");
try
{
var succeed = false;
await Task.Run(() =>
{
var result = client.BeginConnect(ip, port, null, null);
succeed = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5)); // timeout doesn't work
client.EndConnect(result);
});
if (succeed && client.Connected)
{
Console.WriteLine("connected to server.");
}
else
{
Console.WriteLine("failed to connect to server.");
}
}
catch (Exception e)
{
Console.WriteLine("exception: " + e.ToString());
}
}
}
}
the connect method doesn't end after 5 seconds as expected, as long as exception thrown, the code after client.BeginConnect(ip, port, null, null); will never get executed.