Trying to implement a timeout parameter for connecting to a server but I'm not having much luck. Here's my code:

client = new TcpClient();

Task task = Task.Factory.FromAsync(client.BeginConnect, client.EndConnect, host, port, null);

bool taskCompleted = connectTask.Wait(timeoutInMS);

if (taskCompleted)
{
    // Do something with the establishment of a successful connection
}
else
{
    Console.WriteLine("Timeout!");
}

Unfortunately if timeoutInMS is greater than 1022, an AggregateException is thrown on this line:

bool taskCompleted = connectTask.Wait(timeoutInMS);

Adjusting the timeout properties of the TcpClient didn't seem to make any differences.

有帮助吗?

解决方案

Most probably because the Task has not produced a result yet in 1022 ms. But waiting for a bit more than that, the task was able to capture the SocketException thrown by TcpClient.

Your situation is analogous to the following:

var task = Task.Factory.StartNew(() =>
{
  Thread.Sleep(5000);
  throw new Exception();
});

bool taskCompleted = task.Wait(4000); // No exception
bool taskCompleted = task.Wait(6000); // Exception

By the way, why are you using FromAsync() when you are using TcpClient in a syncrhonous manner?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top