Multi-threading with .Net HttpListener

后端 未结 5 1573
盖世英雄少女心
盖世英雄少女心 2020-12-02 07:33

I have a listener:

listener = new HttpListener();
listener.Prefixes.Add(@\"http://+:8077/\");
listener.Start();
listenerThread = new Thread(HandleRequests);
         


        
5条回答
  •  死守一世寂寞
    2020-12-02 08:22

    I have consulted my code in EDIT part of my question and I've decided to accept it with some modifications:

    public void Stop() 
    {
        lock (locker)
        {
            isStopping = true;
        }
        resetEvent.WaitOne(); //initially set to true
        listener.Stop();
    }
    
    private void ListenerCallback(IAsyncResult ar)
    {
        lock (locker) //locking on this is a bad idea, but I forget about it before
        {
            if (isStopping)
                return;
    
            resetEvent.Reset();
            numberOfRequests++;
        }
    
        try
        {
            var listener = ar.AsyncState as HttpListener;
    
            var context = listener.EndGetContext(ar);
    
            //do some stuff
        }
        finally //to make sure that bellow code will be executed
        {
            lock (locker)
            {
                if (--numberOfRequests == 0)
                    resetEvent.Set();
            }
        }
    }
    

提交回复
热议问题