在Windows上,C#在数据到达之前或之后,Socket.BeginReceive()是否占用后台线程? [英] On Windows, C#, Does Socket.BeginReceive() take a background thread before or after the data arrives?

查看:291
本文介绍了在Windows上,C#在数据到达之前或之后,Socket.BeginReceive()是否占用后台线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果在数据到达之前需要后台线程,并且当许多连接在等待数据时,将存在太多线程,从而导致性能下降.有没有不用线程就可以等待数据的方法?

解决方案

Socket.BeginReceive()和.NET中的其他异步I/O方法都使用IOCP线程池.简短的版本是,这是一种管理I/O的非常有效的方法.几乎不需要等待I/O完成的成本,即使I/O完成,也可以从线程池线程中调用完成回调,并且仅在完成回调所需的时间里占用该线程. /p>

"IOCP"代表本机Windows API中的"IO完成端口".基本思想是,您可以有一个线程,也可以有一些线程的小集合,都准备为完成大量I/O操作提供服务.这样一来,I/O操作就可以很好地扩展到成千上万个(即使不是上百万个)并发操作,同时仍然只需要相对较少数量的线程即可处理所有这些操作.

因此,请继续使用那些异步I/O API.它们是编写可伸缩I/O代码的最佳方法.

(此外:特别是Socket类具有许多异步选项.具有讽刺意味的是,以...Async结尾的方法不符合新的(er)async/await范式C#,但实际上它们是使用Socket进行I/O最具可扩展性的方法,因为它们不仅使用IOCP线程池,而且还允许您重用I/O状态对象,因此您可以并最大程度地减少GC负载.)

If it take a background thread before the data arrives, and when many connections waiting for data, there will be too many threads exist, causing performance degradation. is there an approach to wait for data without taking a thread?

解决方案

Socket.BeginReceive(), and other asynchronous I/O methods in .NET, make use of the IOCP thread pool. The short version is that this is a very efficient way to manage I/O. There is practically no cost to wait for the I/O to complete, and even once it completes, your completion callback is called from a thread pool thread, tying up that thread only for as long as it takes for your callback to complete.

"IOCP" stands for "IO Completion Ports", a feature in the native Windows API. The basic idea is that you can have a single thread, or some small collection of threads, all ready to service the completion of a large number of I/O operations. This allows I/O operations to scale well into the hundreds of thousands, if not millions, of concurrent operations, while still only requiring a relatively small number of threads to deal with them all.

So, go right ahead use those asynchronous I/O APIs. They are the best way to write scalable I/O code.

(Aside: the Socket class in particular has a number of async options. Ironically, the methods ending in ...Async do not comply with the new(er) async/await paradigm in C#, but they are in fact the most scalable way to do I/O with a Socket, because not only do they use the IOCP thread pool, they also allow you to reuse your I/O state objects, so you can have a pool of those and minimize GC load.)

这篇关于在Windows上,C#在数据到达之前或之后,Socket.BeginReceive()是否占用后台线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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