HttpListeners and ports

5.3k Views Asked by At

I am creating an HttpListener by attempting to grab a random port that is open (or one that is not in IpGlobalProperties.GetActiveTcpConnections()). The issue I am running into is that after a while of making these connections and disposing them I am getting this error : No more memory is available for security information updates Is there any way to resolve this or is there a proper way of getting rid of HttpListeners. I am just calling listener.Close().

Here is the method used to create the listeners :


private HttpListener CreateListener()
        {
            HttpListener httpListener;
            DateTime timeout = DateTime.Now.AddSeconds(30);
            bool foundPort = false;
            do
            {
                httpListener = new HttpListener();
                Port = GetAvailablePort();
                string uriPref = string.Format("http://{0}:{1}/", Environment.MachineName.ToLower(), Port);
                httpListener.Prefixes.Add(uriPref);
                try
                {
                    httpListener.Start();
                    foundPort = true;
                    break;
                }
                catch
                {
                    httpListener.Close();
                    FailedPorts.Add(Port);
                }
            } while (DateTime.Now < timeout);

        if (!foundPort)
            throw new NoAvailablePortException();

        return httpListener;
    }

3

There are 3 best solutions below

0
On BEST ANSWER

This is the hackish way to force HttpListener to unregister all your Prefixes associated with that httpListener (this uses some of my custom reflection libraries but the basic idea is the same)


private void StopListening()
{
    Reflection.ReflectionHelper.InvokeMethod(httpListener, "RemoveAll", new object[] {false});
    httpListener.Close();
    pendingRequestQueue.Clear(); //this is something we use but just in case you have some requests clear them
}

7
On

Have you tried calling listener.Stop() before Close()?

Another thing to try is to wrap your code in a using() {} block to make sure your object is disposed properly.

Finally, what are you doing with the listener (a code snippet might help)? Are you leaving any streams open?

0
On

You need to remove the failed prefix before adding a new one, which is a lot simpler then Jesus Ramos proposed.

httpListener.Prefixes.Remove(uriPref);