简体   繁体   English

C#非阻塞套接字没有while(true)循环

[英]C# non-blocking socket without while(true) loop

I'm just trying to make some socket programming, using non-blocking sockets in c#. 我只是想在c#中使用非阻塞套接字进行一些套接字编程。 The various samples that i've found, such as this , seems to use a while(true) loop, but this approach causes the cpu to burst at 100%. 我发现的各种样本,比如这样 ,似乎使用了一个while(true)循环,但是这种方法会导致cpu突然达到100%。 Is there a way to use non-blocking sockets using a event programming style? 有没有办法使用事件编程风格的非阻塞套接字? Thanks 谢谢

See the MSDN example here . 请参阅此处的MSDN示例。 The example shows how to receive data asynchronously. 该示例显示了如何异步接收数据。 You can also use the Socket BeginSend/EndSend methods to send data asynchronously. 您还可以使用Socket BeginSend / EndSend方法异步发送数据。

You should note that the callback delegate executes in the context of a ThreadPool thread. 您应该注意,回调委托在ThreadPool线程的上下文中执行。 This is important if the data received inside the callback needs to be shared with another thread, eg, the main UI thread that displays the data in a Windows form. 如果回调内部接收的数据需要与另一个线程共享,这很重要,例如,以Windows窗体显示数据的主UI线程。 If so, you will need to synchronized access to the data using the lock keyword, for example. 如果是这样,您将需要使用lock关键字同步对数据的访问权限。

As you've noticed, with nonblocking sockets and a while loop, the processor is pegged at 100%. 正如您所注意到的那样,使用非阻塞套接字和while循环,处理器固定为100%。 The asynchronous model will only invoke the callback delegate when there is data to send or receive. 异步模型仅在有数据要发送或接收时才调用回调委托。

To avoid a CPU issue in heavy while loop, when no data receive put thread.sleep(100) or less. 为了避免在繁重的while循环中出现CPU问题,当没有数据接收时放入thread.sleep(100)或更少。 That will let other processes change to do their task 这将让其他流程改变以完成他们的任务

Talking generally about blocking/non-blocking IO, applicable generally: 一般性地谈论阻塞/非阻塞IO,一般适用:

The key thing is that in real life your program does other things whilst not doing IO. 关键是在现实生活中,你的程序做其他事情而不做IO。 The examples are all contrived in this way. 这些例子都是以这种方式设计的。

In blocking IO, your thread 'blocks' while waiting for IO. 在阻塞IO时,您的线程在等待IO时“阻塞”。 The OS goes and does other things, eg allows other threads to run. 操作系统会执行其他操作,例如允许其他线程运行。 So your application can do many things (conceptually) in parallel by using many threads. 因此,您的应用程序可以通过使用许多线程并行地(概念上)执行许多操作。

In non-blocking IO, your thread queries to see if IO is possible, and otherwise goes and does something else. 在非阻塞IO中,您的线程会查询IO是否可行,否则会执行其他操作。 So you do many things in parallel by explicitly - at an application level - swapping between them. 因此,您可以通过显式地 - 在应用程序级别 - 并行处理来并行执行许多操作。

Socket.BeginReceive和AsyncCallback

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM