Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-blocking Sockets vs BeginXXX vs SocketAsyncEventArgs

Can anyone please enlighten me about current .NET socket techniques?

  1. Non-blocking sockets

    If I set Socket.Blocking = false and use async operations - what will happen?

    Is there any method of polling multiple non-blocking sockets instead of checking them for availability one-by-one (something like trivial select() or any other mechanism, some IOCP-related may be) aside from Socket.Select()?

  2. BeginXXX and SocketAsyncEventArgs

    Are they operating on blocking sockets under the hood and just hide thread creation?

    Will manual creation of threads be equal to using BeginXXX methods?

    Is there any other pros on using SocketAsyncEventArgs other then it allows to create pool of sockets and everything related to them?

And one final question: if app is working as some kind of heavily loaded binary proxy with most logic done in single thread - what provides better scalability: non-blocking approach or async operations?

like image 848
Aquilae Avatar asked Feb 27 '12 10:02

Aquilae


People also ask

How can you tell if a socket is blocking or non blocking?

From MSDN, the return value of connect(): On a blocking socket, the return value indicates success or failure of the connection attempt. With a nonblocking socket, the connection attempt cannot be completed immediately. In this case, connect will return SOCKET_ERROR , and WSAGetLastError() will return WSAEWOULDBLOCK.

Is Select function is blocking?

By using the select() call, you do not issue a blocking call until you know that the call cannot block. The select() call can itself be blocking, nonblocking, or, for the macro API, asynchronous.


1 Answers

1: Socket.Select should do that, although I don't tend to use that approach personally; in particular those IList get annoying at high volumes

2: no, other way around; the blocking operations are essentially using the non-blocking in the background, but with gates. No, they don't create threads under the hood - unless you count the callback when something is inbound. I have an example here that is serving 12k connections using SocketAsyncEventArgs - the thread count is something like 20. Among the intentions of SocketAsyncEventArgs is that:

  • it is far easier to pool effectively, without having lots of objects created/collected per operation
  • you can handle the "data is available now" scenario very efficiently without needing a callback at all (if the method returns false, you are meant to process the data immediately - no callback will be forthcoming)

For scalability: async

like image 131
Marc Gravell Avatar answered Nov 15 '22 00:11

Marc Gravell