Asynchronous network programming with async/await

后端 未结 2 630
别跟我提以往
别跟我提以往 2021-01-28 08:33

For the past few years, I\'ve developed client/server software using the Asynchronous Programming Model and sockets. This example on MSDN, although overcomplicated with synchron

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-28 08:43

    Actually, the old APM supported by the Socket class used a special thread pool, the IOCP ("I/O Completion Port") thread pool, and rather than assigning threads "when data is received", actually assigned threads as I/O operations are initiated, but in a way that allows a single thread (or small number of threads…e.g. as many as there are cores on the system) to handle a large number of socket objects and operations.

    As far as how to use the new async/await style API, unfortunately the Socket class didn't get any direct async love. However, all of the wrappers did. The most straight-forward replacement is to use the NetworkStream class, and use ReadAsync() and WriteAsync(), which are awaitable methods.

    If you want to still use the Socket API (essentially) directly, you'll have to wrap it yourself with an awaitable implementation. IMHO, a very good resource explaining one possible approach for doing this is here: Awaiting Socket Operations

提交回复
热议问题