gpt4 book ai didi

c# - 为什么等待此任务 1022 毫秒工作正常,但 1023 会导致 AggregateException?

转载 作者:搜寻专家 更新时间:2023-11-01 09:11:50 25 4
gpt4 key购买 nike

尝试实现连接到服务器的超时参数,但运气不佳。这是我的代码:

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!");
}

不幸的是,如果 timeoutInMS 大于 1022,则会在该行抛出 AggregateException:

bool taskCompleted = connectTask.Wait(timeoutInMS);

调整 TcpClient 的超时属性似乎没有任何区别。

最佳答案

很可能是因为 Task 在 1022 毫秒内尚未产生结果。但稍等片刻,任务就能够捕获 TcpClient 抛出的 SocketException

您的情况类似于以下情况:

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

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

顺便问一下,当您以同步方式使用 TcpClient 时,为什么要使用 FromAsync()

关于c# - 为什么等待此任务 1022 毫秒工作正常,但 1023 会导致 AggregateException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7735129/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com