Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Net.HttpListener only explicitly implements IDisposable

Tags:

.net

Why does HttpListener explicitly implement IDisposable. This means you have to cast to IDisposable before calling dispose and in my opinion makes the fact you have to call dispose less obvious.

like image 802
avid Avatar asked Jun 06 '11 12:06

avid


People also ask

What does HttpListener do?

Using the HttpListener class, you can create a simple HTTP protocol listener that responds to HTTP requests. The listener is active for the lifetime of the HttpListener object and runs within your application with its permissions.

What is HttpListener in c#?

The Hypertext Transfer Protocol (HTTP) is an application protocol for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web. HttpListener is a simple, programmatically controlled HTTP protocol listener. It can be used to create HTTP servers.

What does IDisposable mean?

IDisposable is an interface that contains a single method, Dispose(), for releasing unmanaged resources, like files, streams, database connections and so on.

Where is IDisposable used?

You should implement IDisposable only if your class uses unmanaged resources directly. It is a breaking change to add the IDisposable interface to an existing class because pre-existing clients of the class cannot call Dispose(), so you cannot be certain that unmanaged resources held by your class will be released.


1 Answers

  1. You don't need an explicit cast if you use a using block. (This is the preferred idiom, where possible, for dealing with IDisposable objects.)

    using (HttpListener hl = /* ... */)
    {
        // ...
    }
    
  2. It has a Close method which is pretty-much an alias for Dispose. (Not my favourite pattern, but the framework designers seem to like it!)

    HttpListener hl = /* ... */
    try
    {
        // ...
    }
    finally
    {
        hl.Close();
    }
    
like image 170
LukeH Avatar answered Sep 27 '22 19:09

LukeH