在未连接的套接字上不允许该操作

The operation is not allowed on non-connected sockets

我是异步编程的新手,我认为这可能是我的问题,但查看其他答案后,我不确定是否找到适合我情况的答案。

我正在尝试使用 TcpClient 连接到服务器和端口并从中获取流,但出现以下错误:

The operation is not allowed on non-connected sockets

我只能假设这是因为异步连接

Another confusion point for me is that it seems TcpClient has a Connect not just ConnectAsync TcpClient Connect method but it won't build with the error that TcpClient does not contain a definition for Connect.

还有我尝试使用的此文档,似乎 GetStream 是答案,但我不确定我是否正确实施了它。 .NET Core TcpClient

using (var irc = new TcpClient())
{
    irc.ConnectAsync(_server, _port);

    using (var stream = irc.GetStream())
    using (var reader = new StreamReader(stream))
    using (var writer = new StreamWriter(stream))
    {
      // Rest of code
    }
}

代码不会等待连接完成。问题不是由 ConnectAsync 引起的,而是因为在客户端有机会连接之前调用了 GetStream

只需将您的代码更改为:

await irc.ConnectAsync(_server, _port);

为了使用 await,您必须将封闭方法的签名更改为 async Taskasync Task<something>,如果结果 return:

async Task MyMethodAsync()
{
    ...
    await irc.ConnectAsync(_server, _port);
    ...
}

async Task<string> MyMethodAsync()
{
    ...
    await irc.ConnectAsync(_server, _port);
    ...
    return result;
}

不要 尝试阻止任何使用 .Wait().Result 的异步调用。这将阻塞原始线程并可能导致死锁。如果你最终阻塞了它,那么调用异步方法就没有意义了。

也不要使用 async void 签名。这仅为异步事件处理程序保留。 return 没有结果的方法应该有 async Task 签名