异步网络编程与异步/的await [英] Asynchronous network programming with async/await

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

问题描述

在过去的几年中,我已经开发使用异步编程模型和插座的客户机/服务器软件。这 的例子在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.

最近有人提到,这种方法也可以用在异步/的await模型引入了.NET 4.5来实现,因此利用任务和使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?

推荐答案

事实上,由插座类支持的老APM采用了特殊的线程池,IOCP( I / O完成端口),线程池,而非分配线程接收数据时,实际分配线程为I / O操作的启动的,但在某种程度上,它允许一个线程(或少数线程&hellip的。例如,许多因为有系统上的内核)来处理大量的套接字对象和操作的

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.

至于如何使用新的异步 / 的await 风格的API,不幸的是,插槽类没有得到任何直接的异步爱情。然而,所有的包装器一样。最直接的替代是使用的NetworkStream 类,并使用 ReadAsync() WriteAsync(),这是awaitable方法。

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.

如果您想还是用插座 API(本质)直接,你必须自己用awaitable实现包裹。恕我直言,一个非常好的资源解释这样做的一种可能的方法是在这里:的等待套接字操作

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

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

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