darkey darkey - 1 year ago 131
C# Question

Why HttpListener Start method Dispose stuff on exception ?

There is something that I really don't understand with the HttpListener.

The code below speaks for itself and expose the "issue" in one way.

I simply instantiate two different HttpListener with the same single prefix for each one.
I then start the first listener, and of course I get an HttpListenerException when I try to start the second one (same prefix) .. so far so good.

Ok my fault (or the end user fault if we are going through a configuration tool). No panic, I will just clear the prefix of the second listener and specify a new one ... or stop the first listener and try to restart the second one, or whatever ...

But can't do all of this because as soon as I am trying to access the second listener Prefixes or anything else, I get an ObjectDisposedException (Cannot access a disposed object. Object name: 'System.Net.HttpListener').

My question is WHY ?
I do not see anything in HttpListener documentation specifying that on a HttpListenerException some inner stuff of HttpListener object is somehow disposed and the object is just useless from that point on ...

So this means that if I am starting an HttpListener and get an HttpListenerException I have to recreate a whole new HttpListener object in any case ? Seems a little bit weird for me (but there may be another way or a very good reason).

Thanks in advance for your answers !!

var listener1 = new HttpListener();

var listener2 = new HttpListener();

catch (HttpListenerException ex)
listener2.Prefixes.Clear(); // BAM ! ObjectDisposedException

Answer Source

An exception means something has gone horribly wrong. Rather than allow unsuspecting consumers to continue to use a possibly corrupt and unstable object, it instead disposes of itself. Just create the new listener, and be happy that you don't have to worry about using a possibly useless object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download