Socket.ListenBacklog Property
This property defines the maximum number of pending connections that the operating system will queue for the Socket.Accept method. When the backlog is full, new connection requests may be rejected by the server.
Syntax
public int ListenBacklog { get; set; }
Parameters
| Name | Type | Description |
|---|---|---|
Value |
int |
The maximum number of connections to queue. A value of -1 (or 0 in some implementations) indicates the system default. |
Remarks
The ListenBacklog property is crucial for managing the capacity of a server application to handle incoming connection requests. A higher backlog value allows the server to queue more incoming connection attempts before needing to accept them, which can be beneficial in scenarios with many short-lived connections or sudden bursts of traffic. However, setting an excessively high backlog can consume significant system resources and may not always lead to improved performance.
The default value for the backlog can vary across operating systems and network configurations. It is generally recommended to tune this value based on the specific needs and expected load of your application.
When the backlog queue is full, the server's operating system may drop new incoming connection requests. This can lead to clients experiencing connection timeouts or failures.
Best Practice
For most common server applications, a backlog value between 100 and 1000 is a reasonable starting point. Monitor your server's performance and client connection success rates to determine the optimal value. Consider using a value of -1 to rely on the system's default if you are unsure.
Example
The following example demonstrates how to set the backlog for a listening socket.
using System;
using System.Net;
using System.Net.Sockets;
public class SocketListener
{
public static void StartListening(int port)
{
var ipAddress = IPAddress.Any;
var localEndPoint = new IPEndPoint(ipAddress, port);
using (Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
// Set the backlog to 100 pending connections
listener.ListenBacklog = 100;
listener.Bind(localEndPoint);
listener.Listen(listener.ListenBacklog); // The parameter here is often ignored when ListenBacklog is set
Console.WriteLine($"Listening on {localEndPoint} with a backlog of {listener.ListenBacklog}");
// ... Accept connections ...
}
}
}
Note on Socket.Listen() parameter
The Socket.Listen(int backlog) method also takes a backlog parameter. When the ListenBacklog property is set explicitly before calling Listen(), the value provided to the Listen() method might be redundant or overridden by the property's value on some .NET versions or underlying OS implementations. It's generally considered good practice to set the ListenBacklog property for clarity and consistency.