Test case:
using System;
using System.Net;
namespace HttpListenerTest {
class Listener {
static void Main(string[] args) {
HttpListener listener = new HttpListener();
listener.IgnoreWriteExceptions = true;
listener.Prefixes.Add("http://*:8000/");
listener.Start();
Console.WriteLine("listening...");
listener.BeginGetContext(RequestHandler, listener);
while(true) {
System.Threading.Thread.Sleep(250);
}
}
static void RequestHandler(IAsyncResult ar) {
HttpListenerContext httpContext = null;
try {
HttpListener listener = (HttpListener)ar.AsyncState;
httpContext = listener.EndGetContext(ar);
// start listening for next request
listener.BeginGetContext(RequestHandler, listener);
// invoke response handler
ResponseHandler(httpContext);
} catch(Exception e) {
Console.WriteLine(e.ToString());
if(httpContext != null)
httpContext.Response.Close();
}
}
static void ResponseHandler(HttpListenerContext httpContext) {
byte[] buffer = System.Text.Encoding.ASCII.GetBytes("hello world");
httpContext.Response.OutputStream.Write(buffer, 0, buffer.Length);
httpContext.Response.Close();
}
}
}
With server running, send a get
curl http://localhost:8000
Exception:
[root@buildmonkey:~] /opt/mono-2.2/bin/mono HttpListener.exe listening... System.IO.IOException: BeginReceive failure ---> System.ObjectDisposedException: The object was used after being disposed. at System.Net.Sockets.Socket.BeginReceive (System.Byte[] buffer, Int32 offset, Int32 size, SocketFlags socket_flags, System.AsyncCallback callback, System.Object state) [0x00000] at System.Net.Sockets.NetworkStream.BeginRead (System.Byte[] buffer, Int32 offset, Int32 size, System.AsyncCallback callback, System.Object state) [0x00000] --- End of inner exception stack trace --- at System.Net.Sockets.NetworkStream.BeginRead (System.Byte[] buffer, Int32 offset, Int32 size, System.AsyncCallback callback, System.Object state) [0x00000] at System.Net.HttpConnection.BeginReadRequest () [0x00000] at System.Net.HttpConnection.Close () [0x00000] at System.Net.HttpListenerResponse.Close (Boolean force) [0x00000] at System.Net.HttpListenerResponse.Close () [0x00000] at HttpListenerTest.Listener.ResponseHandler (System.Net.HttpListenerContext httpContext) [0x00000] at HttpListenerTest.Listener.RequestHandler (IAsyncResult ar) [0x00000]