views:

1171

answers:

3

I'm just trying to make some socket programming, using non-blocking sockets in 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%. Is there a way to use non-blocking sockets using a event programming style? Thanks

+2  A: 

Talking generally about blocking/non-blocking IO, applicable generally:

The key thing is that in real life your program does other things whilst not doing IO. The examples are all contrived in this way.

In blocking IO, your thread 'blocks' while waiting for IO. The OS goes and does other things, e.g. 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. So you do many things in parallel by explicitly - at an application level - swapping between them.

Will
A: 

Socket.BeginReceive and AsyncCallback

danbystrom
+1  A: 

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

You should note that the callback delegate executes in the context of a ThreadPool thread. This is important if the data received inside the callback needs to be shared with another thread, e.g., the main UI thread that displays the data in a Windows form. If so, you will need to synchronized access to the data using the lock keyword, for example.

As you've noticed, with nonblocking sockets and a while loop, the processor is pegged at 100%. The asynchronous model will only invoke the callback delegate when there is data to send or receive.

Matt Davis