I have a simple HTTPServer implementation, that use the System.Net.HttpListener. It seems that my AsyncCallbacks isn't diposed somehow, and therefore is leading to a leak.
public abstract class HttpServer : IHttpServer, IDisposable
{
protected readonly HttpListener HttpListener = new HttpListener();
protected HttpServer(IEnumerable<string> prefixes)
{
WaitOnStartup = new AutoResetEvent(false);
foreach (var prefix in prefixes)
{
HttpListener.Prefixes.Add(prefix);
}
}
private void Process()
{
var result = HttpListener.BeginGetContext(ContextReceived, HttpListener);
result.AsyncWaitHandle.WaitOne(30000);
result.AsyncWaitHandle.Dispose();
}
protected abstract void ContextReceived(IAsyncResult ar);
[...]
}
public class MyHttpServer : HttpServer
{
public MyHttpServer(IEnumerable<string> prefixes) : base(prefixes) { }
protected override void ContextReceived(IAsyncResult ar)
{
var listener = ar.AsyncState as HttpListener;
if (listener == null) return;
var context = listener.EndGetContext(ar);
try
{
var request = context.Request;
var response = context.Response;
//handle the request...
}
finally
{
context.Response.Close();
listener.Close();
}
}
}
If I run a memory profiler it looks like the async handle (BeginGetContext) isn't disposed, which means that AsyncCallback objects keep increasing....
What did I miss??
UPDATE 11:45:
Here is the Dipose() of the base class (HttpServer)
protected virtual void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
// Free any other managed objects here.
HttpListener.Stop();
HttpListener.Close();
WaitOnStartup.Dispose();
}
// Free any unmanaged objects here.
//
_disposed = true;
}