使用 async/await 进行异步网络编程 [英] Asynchronous network programming with async/await

查看:31
本文介绍了使用 async/await 进行异步网络编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在过去的几年中,我使用异步编程模型和套接字开发了客户端/服务器软件.这个 example 在 MSDN 上,虽然过于复杂使用 ManualResetEvents 等同步机制说明了这些概念:您使用 BeginXXX()EndXXX() 方法对进行连接和流操作.

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 synchronisation mechanisms such as ManualResetEvents, illustrates the concepts: you use a BeginXXX() and EndXXX() method pair for the connection and stream operations.

这样做的好处是让线程池根据需要(例如,当接收到数据时)分配线程,而不是每个连接都有一个专用线程,这无法扩展.

This has the advantage of letting the thread pool assign threads as needed (e.g. when data is received) rather than having a dedicated thread per connection, which doesn't scale.

最近有人提到,这种方法也可以使用 .NET 4.5 中引入的 async/await 模型来实现,因此在这种情况下使用 Tasks 并使 APM 变得不必要.这是怎么做到的?

Someone recently mentioned that this approach can also be achieved using the async/await model introduced in .NET 4.5, thus using Tasks and making the APM unnecessary for this scenario. How is this done?

推荐答案

其实Socket类支持的老APM使用了一个特殊的线程池,IOCP("I/O Completion Port") 线程池,而不是在接收到数据时"分配线程,实际上分配线程作为 I/O 操作是启动,但是以允许单个线程(或少量线程)的方式…例如,与系统上的内核一样多)来处理大量的套接字对象和操作.

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.

至于如何使用新的 async/await 风格的 API,不幸的是 Socket 类没有得到任何直接的 异步爱.然而,所有的包装器都做到了.最直接的替代方法是使用 NetworkStream 类,并使用 ReadAsync()WriteAsync(),它们是可等待的方法.

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.

如果您仍想直接(基本上)使用 Socket API,您必须自己使用可等待的实现来包装它.恕我直言,这里有一个很好的资源来解释这样做的一种可能方法:等待套接字操作

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

这篇关于使用 async/await 进行异步网络编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆