If you can use async/await then potentially you are using .NET 4.5. If so you can use the AcceptSocketAsync
or AcceptTcpClientAsync
methods on TcpListener
? For example:
await listener.AcceptSocketAsync();
The Pending
method does the same checks as these two methods but just returns immediately with a true
/false
. The two Accept...Async
are designed to block until Pending
would otherwise return true
and then hand you your Socket
or TcpClient
respectively.
Background
From the Pending
documentation:
This non-blocking method determines if there are any pending connection requests. Because the AcceptSocket and AcceptTcpClient methods block execution until the Start method has queued an incoming connection request, the Pending method can be used to determine if connections are available before attempting to accept them.
The Accept...Async
methods do the same as the Accept...
versions, but you can await
them.