Why HttpListener Start method Dispose stuff on exception ?

那年仲夏 提交于 2020-01-05 05:30:09

问题


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();
listener1.Prefixes.Add("http://localhost:8080/MyHandler/");
listener1.Start();

var listener2 = new HttpListener();
listener2.Prefixes.Add("http://localhost:8080/MyHandler/");

try
{
   listener2.Start();
}
catch (HttpListenerException ex)
{
  listener2.Prefixes.Clear(); // BAM ! ObjectDisposedException
}

回答1:


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.



来源:https://stackoverflow.com/questions/11164919/why-httplistener-start-method-dispose-stuff-on-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!