Webserver Proper Startup and Terminate

Does anybody know the proper way so you can start and stop a webserver using the Interface_WirelessConnectivityChanged Event?


private void RunServer()
        {
            HttpListener listener = new HttpListener("http");
            listener.Start();
            
            while (webServerAlive)
            {
                HttpListenerResponse response = null;
                HttpListenerContext context = null;

                if ((_wifi.Interface.IsLinkConnected) && (listener.IsListening))
                {
                    try
                    {
                        context = listener.GetContext();
                        response = context.Response;
                        HttpListenerRequest request = context.Request;
                        switch (request.HttpMethod.ToUpper())
                        {
                            case "GET": ProcessClientGetRequest(context); break;
                        }

                        if (response != null)
                        {
                            response.Close();
                        }
                    }
                    catch
                    {
                        if (context != null)
                        {
                            context.Close();
                        }
                    }
                }

                System.Threading.Thread.Sleep(500);
            }

            listener.Stop();
            listener = null;
        }

private void Interface_WirelessConnectivityChanged(object sender, WiFiRS9110.WirelessConnectivityEventArgs e)
        {
            try
            {
                if (e.IsConnected)
                {
                    // got a network connected event, set info

                    Status = WiFiStatus.Connected;

                    NetworkInterface = _wifi.Interface.NetworkInterface;

                    // if the consumer wants to check NIST - if so, do it in a thrad
                    Thread t = new Thread(new ThreadStart(DoTimeUpdate));
                    t.Start();

                    webServer = new Thread(RunServer);
                    webServer.Priority = ThreadPriority.BelowNormal;
                    webServerAlive = true;
                    webServer.Start();
                }
                else
                {
                    webServerAlive = false;
                    webServer.Join(1000);

                    NetworkInterface = null;
                    CurrentInfo = null;

                    Status = WiFiStatus.NotConnected;
                }
            }
            catch (Exception ee)
            {
                if (LogRequested != null)
                {
                    LogRequested(null, new LogRequestArgs(ee.Message));
                }
            }
        }

When I connect Wifi back I get this error on this line


listener.Start();

The thread ‘’ (0x14) has exited with code 0 (0x0).
#### Exception System.Net.Sockets.SocketException - CLR_E_FAIL (21) ####
#### Message:
#### Microsoft.SPOT.Net.SocketNative::bind [IP: 0000] ####
#### System.Net.Sockets.Socket::Bind [IP: 0016] ####
#### System.Net.HttpListener::Start [IP: 005b] ####
#### FishTankControlSystem_2.WiFiModule::RunServer [IP: 000b] ####
#### SocketException ErrorCode = 10048
#### SocketException ErrorCode = 10048
A first chance exception of type ‘System.Net.Sockets.SocketException’ occurred in Microsoft.SPOT.Net.dll
#### SocketException ErrorCode = 10048
An unhandled exception of type ‘System.Net.Sockets.SocketException’ occurred in Microsoft.SPOT.Net.dll

I modified my code to be this


HttpListenerRequest request;
            int failedAttempts = 0;

            HttpListener listener = new HttpListener("http");

            TryAgain:
            try
            {
                listener.Start();
            }
            catch (Exception e)
            {
                if (failedAttempts < 50)
                {
                    failedAttempts += 1;
                    Thread.Sleep(1);
                    goto TryAgain;
                }
            }

It works after 31 failed attempts always. I believe the httplistener class is not releasing the port or something is not releasing the port. The error I get is

The error code means [Windows Sockets Error Codes (Winsock2.h) - Win32 apps | Microsoft Learn]: