我一直在寻找很多例子,例如this,this和this,但它们都不起作用。我不确定有什么问题,但是对于我尝试过的每个示例而言,等待只是被忽略,并且我只在大约1秒内得到标准的未处理的套接字异常,而不管指定的等待时间。 No connection could be made because the target machine actively refused it.
如何使用TcpClient设置异步连接的超时时间?
下面是摘录,以帮助理解:
public void Connect(string host, int port)
{
tcpClient.BeginConnect(host, port, OnConnect, null);
}
private void OnConnect(IAsyncResult async)
{
tcpClient.EndConnect(async);
}
一直在尝试了一堆不同的例子,但我的客户端应用程序要么只是failsfast后个个第二或抛出一个插座例外。 try-catch是否会成为更好的解决方案,并避免使用WaitHandles?
所有这些例子都应该有效。通过您的代码使用第一个结束步骤。在调用EndConnect之前,无法获得套接字错误。 – jgauffin