简体   繁体   English

未连接的插座上不允许进行该操作

[英]The operation is not allowed on non-connected sockets

I'm new to async programming which I think might be my problem here but checking out other answers, I'm not sure I find one that fits my situation. 我是异步编程的新手,我认为这可能是我的问题,但请查看其他答案,我不确定是否找到适合自己情况的答案。

I'm attemping to use the TcpClient to connect to a server and port and get the stream from that but I get an error of: 我正在尝试使用TcpClient连接到服务器和端口并从中获取流,但是出现以下错误:

The operation is not allowed on non-connected sockets 未连接的插座上不允许进行该操作

I can only assume this is because of the async connect 我只能假设这是由于异步连接

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. 对我来说,另一个困惑点是,似乎TcpClient不仅具有ConnectAsync TcpClient Connect方法,还具有Connect,但它不会生成TcpClient不包含Connect定义的错误。

There's also this documentation I tried to use and it seems GetStream is the answer but I'm not sure I'm implementing it correctly. 还有我尝试使用的这份文档,看来GetStream是答案,但我不确定我是否正确实现了它。 .NET Core TcpClient .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
    }
}

The code doesn't await for the connection to finish. 该代码不会等待连接完成。 The problem isn't caused by ConnectAsync, its caused because GetStream is called before the client had a chance to connect 该问题不是由ConnectAsync引起的,其原因是因为在客户端有机会连接之前调用GetStream

Just change your code to : 只需将代码更改为:

await irc.ConnectAsync(_server, _port);

In order to use await you'll have to change the signature of the enclosing method to async Task or async Task<something> if it returns a result: 为了使用await您必须将封闭方法的签名更改为async Taskasync Task<something>如果返回结果):

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

or 要么

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

DON'T try to block any asynchronous calls with .Wait() or .Result . 不要尝试使用.Wait().Result阻止任何异步调用。 This will block the original thread and probably result in deadlocks. 这将阻塞原始线程,并可能导致死锁。 There's no point in calling an asynchronous method if you end up blocking on it after all. 如果最终阻塞了异步方法,那么调用异步方法毫无意义。

Don't use the async void signature either. 也不要使用async void签名。 This is reserved only for asynchronous event handlers. 这仅保留给异步事件处理程序。 Methods that return no result should have an async Task signature 不返回结果的方法应具有async Task签名

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM