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

I'm just trying to do some sort of socket programming using non-blocking sockets in C #. Various samples I found, like this , seem to use a while (true) loop, but this approach causes the processor to burst 100%. Is there a way to use non-blocking sockets using the event programming style? Thanks

+6
c # while-loop nonblocking sockets
source share
4 answers

See the MSDN example here . This example shows how to receive data asynchronously. You can also use the Socket BeginSend / EndSend methods to send data asynchronously.

It should be noted that the callback delegate is executed in the context of the ThreadPool thread. This is important if the data received inside the callback must be shared by another thread, for example, the main thread of the user interface, which displays the data in the form of Windows. If so, you will need to synchronize data access using the lock keyword, for example.

As you noticed, with non-blocking sockets and a while loop, the processor is tied to 100%. The asynchronous model will only call the callback delegate when there is data to send or receive.

+6
source share

To avoid a processor problem in an intense while loop when no data gets put thread.sleep(100) or less. This will allow other processes to change their task.

+4
source share

Speaking generally about blocking / non-blocking IO, applicable in general:

The main thing is that in real life your program does other things without doing IO. Examples are invented in this way.

When IO is blocked, your thread blocks the I / O timeout. The OS goes and does other things, for example. allows you to run other threads. Thus, your application can do many things (conceptually) in parallel, using many threads.

In a non-blocking IO, your thread requests to see if an IO is possible, and otherwise it goes and does something else. Thus, you do many things in parallel, explicitly - at the application level - by exchanging between them.

+3
source share

Socket.BeginReceive and AsyncCallback

0
source share

All Articles