ASP.NET web services leak memory when (de)serializing disposable objects?

Posted by Serilla on Stack Overflow See other posts from Stack Overflow or by Serilla
Published on 2010-04-26T03:11:40Z Indexed on 2010/04/26 3:33 UTC
Read the original article Hit count: 213

In the following two cases, if Customer is disposable (implementing IDisposable), I believe it will not be disposed by ASP.NET, potentially being the cause of a memory leak:

    [WebMethod]
    public Customer FetchCustomer(int id)
    {
        return new Customer(id);
    }

    [WebMethod]
    public void SaveCustomer(Customer value)
    {
      // save it
    }

This flaw applies to any IDisposable object. So returning a DataSet from a ASP.NET web service, for example, will also result in a memory leak - the DataSet will not be disposed.

In my case, Customer opened a database connection which was cleaned up in Dispose - except Dispose was never called resulting in loads of unclosed database connections. I realise there a whole bunch of bad practices being followed here (its only an example anyway), but the point is that ASP.NET - the (de)serializer - is responsible for disposing these objects, so why doesn't it?

This is an issue I was aware of for a while, but never got to the bottom of. I'm hoping somebody can confirm what I have found, and perhaps explain if there is a way of dealing with it.

© Stack Overflow or respective owner

Related posts about web-services

Related posts about asp.net-2.0