Search code examples
c#.netexceptionhttplistener

HttpListeners and ports


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;
    }


Solution

  • 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
    }