开发者

Why does waiting on this Task for 1022 milliseconds work fine but 1023 causes an AggregateException?

开发者 https://www.devze.com 2023-04-12 04:20 出处:网络
Trying to implement a timeout parameter for connecting to a server but I\'m not having much luck. Here\'s my code:

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.EndCon开发者_如何转开发nect, 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?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号