HttpListener异步上下文泄漏

时间:2015-10-08 09:26:40

标签: c# memory-leaks

我有一个简单的HTTPServer实现,它使用System.Net.HttpListener。似乎我的AsyncCallbacks不会以某种方式被放弃,因此导致泄漏。

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();
        }
    }
}

如果我运行内存分析器,它看起来像是不处理异步句柄(BeginGetContext),这意味着AsyncCallback对象不断增加....

我错过了什么?

更新11:45:

这是基类(HttpServer)的Dipose()

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;
}

1 个答案:

答案 0 :(得分:0)

看起来我设法找到了这个问题,我还不确定为什么还要......

但是根据@ {3}}中@ csharptest.net发布的答案的灵感,我替换了使用:

if (a == "") a = "zzzz";

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