public class XhtListener : NetWorker { private HttpListener _listener = new HttpListener(); public XhtListener(IReadOnlyCollection<string> prefixes) { if (!HttpListener.IsSupported) { /// } if (prefixes == null || prefixes.Count == 0) throw new ArgumentException("prefixes"); foreach (var s in prefixes) { _listener.Prefixes.Add(s); } } public override void Start() { if (!WorkFlag) { WorkFlag = true; } var tr = new Thread(() => { while (WorkFlag) { try { _listener.Start();///вот на этом строке if (!_listener.IsListening) continue; HttpListenerContext context; context = _listener.GetContext(); `//////` } 

There is such a code, but when working on this line _listener.Start(); getting
This is the error Cannot access a disposed object. Object name: 'System.Net.HttpListener'. Cannot access a disposed object. Object name: 'System.Net.HttpListener'.

  • four
    Captain Obvious tells: while you were about to call Start () to him, someone managed to call Dispose () on him. - Pavel Mayorov
  • if I don’t use it anywhere else, who else can call it ?? - Vardan Vardanyan
  • 3
    You yourself call. Miracles do not happen. - Pavel Mayorov
  • And how interesting is ????? - Vardan Vardanyan
  • @PavelMayorov with a crooked code miracles happen :). Even in the framework. - andreycha

1 answer 1

This message is misleading, unfortunately. HttpListener throws an HttpListener exception if you are trying to call some method on an instance that is in the closed state. A switch to the closed state of HttpListener can in three cases:

  1. Someone called Dispose() / Close() .
  2. An error occurred during the Start() call.
  3. Someone called Abort() .

So check your code to call Dispose() / Close() / Abort() , as well as exceptions when calling Start() .

A little suspicious looks like the code that you gave. What is there in catch ? Do you have an error when you first call Start() and do you try to call Start() on the same object in a loop?

 while (WorkFlag) { try { _listener.Start();///вот на этом строке if (!_listener.IsListening) continue; HttpListenerContext context; context = _listener.GetContext(); 
  • judging by the _listener code given, it is initialized only once, so the second option looks like the most plausible - Grundy
  • @Grundy Well, since the author did not give the full code, it remains only to guess. Maybe he had other challenges hidden somewhere there :). - andreycha