Search code examples
c#socketsblocking

Purpose of Socket.Blocking


I've been using Begin/EndAccept/Send/Receive methods for sockets in C# for a while, but only recently found out about the Blocking bool option for System.Net.Sockets

Is this a better alternative? If not, what is the purpose of specifying whether or not your Socket should block? It is merely a helpful indicator of whether or not the developer has chosen to implement blocking/non-blocking methods?


Solution

  • Attempting to invoke a Receive call on a blocking socket means that the call won't return until data arrives. When using blocking sockets, your thread is effectively stalled until data is available. So if you try to do socket I/O on the UI thread of a Winforms app, your UI will unresponsive and frozen until data arrives.

    Non-blocking sockets allows your code to do something else. If you call Receive on a non-blocking socket, it will return immediately if there is no data available. Non-blocked sockets are often used in combination with a periodic polling mechanism, "select" style wait call, or other notification mechanism to indicate data is available. .NET also offers the BeginReceive method on the socket as another alternative.

    The choice between "blocking" and "non-blocking" are a design choice. The choice either influences the threading model (or the threading model influences the decision). Both have design implications.

    Early versions of .NET didn't offer BeginReceive IIRC. And async-await wasn't available until much later in .NET versions. Traditional socket models on most platforms are just "send" and "recv" with the option of setting non-blocking mode.