为什么TcpClient.Connect()抛出System.AggregateException

为什么TcpClient.Connect()抛出System.AggregateException,exception,tcp,activemq,tcpclient,aggregateexception,Exception,Tcp,Activemq,Tcpclient,Aggregateexception,我正在尝试使用以下代码检查与本地主机TCP服务器(ActiveMQ代理)的TCP连接: string host = "localhost"; int port = 61616; using (TcpClient tcpClient = new TcpClient()) { try { Task t = Task.Run(() => { tcpClient.Connect(host, port); });

我正在尝试使用以下代码检查与本地主机TCP服务器(ActiveMQ代理)的TCP连接:

string host = "localhost";
int port = 61616;
using (TcpClient tcpClient = new TcpClient())
{
    try
    {


        Task t = Task.Run(() => {
            tcpClient.Connect(host, port);
        });
        Console.WriteLine("Connected.");
        TimeSpan ts = TimeSpan.FromMilliseconds(150);
        if (!t.Wait(ts))
        {
            Console.WriteLine("The timeout interval elapsed.");
            Console.WriteLine("Could not connect to: {0}", port);// ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Port.ToString());
        }
        else
        {
            Console.WriteLine("Port {0} open.", port);
        }
     }
    catch (UnauthorizedAccessException )
    {
        Console.WriteLine("Caught unauthorized access exception-await behavior");
    }
    catch (AggregateException )
    {
        Console.WriteLine("Caught aggregate exception-Task.Wait behavior");
    }
我停止了本地主机服务器(ActiveMQ代理),并尝试运行上述代码。它抛出了
System.aggregateeexception
。当我启动服务器并运行代码时;它连接到服务器

据报道,它将抛出以下其中一项:

  • ArgumentNullException
  • ArgumentOutOfRangeException
  • SocketException
  • ObjectDisposedException
  • SecurityException
  • NotSupportedException
为什么它会抛出System.AggregateException

Task t = Task.Run(() => {
    tcpClient.Connect(host, port);
});
包装您的
.Connect()
调用。而
Task.Run()
总是抛出
aggregateeexception
,其中包含真正的异常。要解决此问题,请检查异常,或者更好地使用异步变量
.Connect()

相反。

我最后做的是:

tcpClient.ReceiveTimeout = 5000;
 tcpClient.SendTimeout = 5000;
 tcpClient.Connect(host, port);
 catch (SocketException) {
                Console.WriteLine("Could not connect to: {0}", port);
                Console.WriteLine("Socket exception. Check host address and port.");
            }

它似乎正在工作。

如果我不在Task.Run()中使用wap,那么如何实现tcp连接超时?tcpclient.readtimeout或writetimeout不工作。这是在
任务中完成的。运行
?如果您的代码在上下文中并且缩进是固定的,这将有所帮助。
tcpClient.ReceiveTimeout = 5000;
 tcpClient.SendTimeout = 5000;
 tcpClient.Connect(host, port);
 catch (SocketException) {
                Console.WriteLine("Could not connect to: {0}", port);
                Console.WriteLine("Socket exception. Check host address and port.");
            }