2

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;
}
grmihel
  • 784
  • 3
  • 15
  • 40

1 Answers1

0

It looks like I managed to find the issue, I'm not excatly sure why yet tho...

But with inspiration from answer posted by @csharptest.net in Multi-threading with .Net HttpListener, I replaced the use of:

private void Process()
{
    var result = HttpListener.BeginGetContext(ContextReceived, HttpListener);
    result.AsyncWaitHandle.WaitOne(30000);
    result.AsyncWaitHandle.Dispose();
}

with

private void Process()
{
    while (HttpListener.IsListening)
    {
        var result = HttpListener.BeginGetContext(ContextReceived,     HttpListener);
        if (WaitHandle.WaitAny(new[] { result.AsyncWaitHandle, _shutdown })     == 0)
            return;
    }
}
Community
  • 1
  • 1
grmihel
  • 784
  • 3
  • 15
  • 40