title: Cannot access a disposed object. Object name: 'System.Net.HttpListener'
body: <p>I am creating a windows service that listens for specific Http requests. I am running an <code>httpListener</code> in a separate task. When the service is stopped i close the listener instance. But it seems that the http listenerContext is waiting for an incoming request and as the listener get closed i get the following error </p>
  
  <pre><code>Cannot access a disposed object. Object name: 'System.Net.HttpListener'.
  </code></pre>
  
  <p>Even if i use some mechanism to inform <code>StartListening()</code> that listening is stopped, it will not run as the execution at the corresponding thread stuck at <code>HttpListenerContext context = await _listener.GetContextAsync();</code>  until a request arrives.  </p>
  
  <pre><code>  public void StartListening() {
           _listener.Start();
           _logger.LogDebug("Http Listening started");
  
           Task.Run(async () =&gt; {
              while (true) {
                 try {
                   if (isOpen == false) {
                   return 0;
                     }
                    HttpListenerContext context = await _listener.GetContextAsync();
                    HttpListenerRequest request = context.Request;
  
                    //processing of the requests url/////
                    var newUri = request.Url.AbsoluteUri;
                    _concurrentUrlQueue.Enqueue(newUri);
                    if (ConcurentUrlQueueChanged != null) ConcurentUrlQueueChanged(this, new EventArgs());
                 }
                 catch (Exception e) {
                    _logger.LogError("Error at get listening  context, Message: " + e.Message);
                 }
  
              }
           });
  
        }    
        public void StopListening() {
            isOpen = false;
           _logger.LogDebug("Http Listening Stop");
           _listener.Close();
  
        }
  </code></pre>
  
  <p>Which is the appropriate way to close an http listener that is listening to get context. The code i use is the following.
  Thank you..</p>