TcpClient vs Socket when dealing with asynchronousy

前端 未结 1 1845
梦谈多话
梦谈多话 2021-01-31 09:26

This is not yet another TcpClient vs Socket.

TcpClient is a wrapper arround the Socket class to ease development, also exposing the underlying Socket.

still ...<

1条回答
  •  梦毁少年i
    2021-01-31 10:18

    Asynchronous I/O on TcpClient streams does not block. It looks like the MSDN docs are wrong (you can verify this in Reflector by following the NetworkStream's async I/O calls).

    Stream types are "interesting": by default, the Stream base class will implement asynchronous I/O by blocking a thread pool thread on synchronous I/O. So you don't ever want to do asynchronous I/O on something like a MemoryStream, which only provides synchronous methods.

    NetworkStream does provide asynchronous I/O, so asynchronous I/O on NetworkStream instances is actually asynchronous. But this is not always the case: FileStream in particular is usually not asynchronous but it is if you construct the instance just right.

    Regarding why Socket doesn't have TAP methods: that is a very good question! I assumed it was an oversight, but now that .NET 4.5 is released, it looks like it was left out on purpose. It could be that they just don't want to overcomplicate the API - Socket already has synchronous and two asynchronous APIs covering the same set of operations (Send, SendTo, Receive, ReceiveFrom, Connect, Accept, Disconnect). TAP would in turn require two additional asynchronous APIs for that full set. That would at least cause an interesting naming situation (the *Async names are already taken, and they'd be adding two more *Async names for each operation).

    Side note: the "additional" APIs are for high-performance asynchronous Socket communication. They use SocketAsyncEventArgs, which is not as easy to use but produces less memory garbage. If TAP APIs were added to Socket, they would want to provide both the easy-to-use versions (wrapping Begin/End) and the higher-performance versions (wrapping Async).

    If you're interesting in making TAP methods for Socket, a good starting point is Stephen Toub's Awaiting Socket Operations (he only provides wrappers for the high-performance API). I use something similar for my async-enabled sockets.

    0 讨论(0)
提交回复
热议问题