private void SocketAcceptedHandler(WebResponseThread requestWorker)
 {
     //_CurrentlyListening = false;
     if (_ListeningID != requestWorker.WorkerID)
     {
         _ListeningID = -1;
         throw (new Exception("_ListeningID != requestWorker.WorkerID"));
     }
     _ListeningID = -1;
 }
 // todo make thread safe
 private void WorkFinishedHandler(Exception ex, WebResponseThread requestWorker)
 {
     if (ex != null)
     {
         Debug.Print("WorkFinishedHandler exception: " + ex.Message);
     }
     _ProcessRequestWorkerList.RemoveAt(requestWorker.WorkerID);
 }
        /// <summary>
        /// Runs the server in its own Thread.
        /// </summary>
        private void RunServer()
        {
            //            Debug.EnableGCMessages(true);// debug only
            using (Socket nonBlockingSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                nonBlockingSocket.Bind(new IPEndPoint(IPAddress.Any, _Port));
                nonBlockingSocket.Listen(1);

                while (!_Stopping)
                {
                    if (_ListeningID == -1)
                    {
                        try
                        {
                            //_CurrentlyListening = true;
                            WebResponseThread currentProcessRequest = new WebResponseThread(ResponseHandler, WorkFinishedHandler, SocketAcceptedHandler);
                            while (_ListeningID < 0)
                            {
                                _ListeningID = _ProcessRequestWorkerList.Enqueue(currentProcessRequest);
                                if (_ListeningID < 0)
                                {
                                    Debug.Print("no spare thread");
                                }
                                Thread.Sleep(50);
                            }
                            currentProcessRequest.Start(nonBlockingSocket);

                        }
                        catch (Exception ex)
                        {// probably lost connection
                            Debug.Print("Exception caught in Run Server: " + ex.Message);
                            _ProcessRequestWorkerList.RemoveAt(_ListeningID);
                            _ListeningID = -1;// what else to do if
                            Thread.Sleep(200);//
                        }
                    }
                }
            }
        }