'Is there a C#.NET 5.0 approach to monitoring TCP port availability for concurrent outgoing network requests?

We have a C#.NET 5.0 application that makes hundreds of thousands of network requests.

To improve performance, we send thousands of concurrent network requests. Sometimes this leads to port exhaustion exceptions.

We would like to prevent exceptions by monitoring port availability and sending another network request only when available ports exists.

E.g.,

var maxOpenPorts = GetMaxOperationSystemOpenPorts();
var openPorts = CountCurrentlyOpenPorts();
var arePortsAvailable = maxOpenPorts > openPorts;

if(!arePortsAvailable) {
  Wait();
}

SendNextNetworkRequest();

How can we GetMaxOperationSystemOpenPorts and CountCurrentlyOpenPorts in .NET 5.0?

P.S. We think that we can count of currently open ports like this:

System.Net.NetworkInformation
   .IPGlobalProperties
   .GetIPGlobalProperties()
   .GetActiveTcpConnections()
   .Count;

We also know how to count open posts from the PowerShell like this:

netstat -o | Select-String ESTABLISHED | Measure-Object


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source