HttpListeners and ports

I am creating an HttpListener trying to capture a random port open (or one that is not in IpGlobalProperties.GetActiveTcpConnections ()). The problem I am facing is that after some time after establishing these connections and removing them, I get this error: No more memory is available for security information updates Is there a way to resolve this or is there a proper way to get rid of HttpListeners. I just call listener.Close ().

Here is the method used to create 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;
    }

code>
+3
source share
3 answers

HttpListener , httpListener ( , )


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
}
+1

listener.Stop() Close()?

, - using() {}, , .

, ( )? - ?

+2

You need to remove the failed prefix before adding a new one, which is much easier than Jesus Ramos suggested.

httpListener.Prefixes.Remove(uriPref);
0
source

Source: https://habr.com/ru/post/1793691/


All Articles