简体   繁体   中英

ASP.Net Application pool memory leak

I have a problem of "Memory Leak" in ASP.Net. I created a blank page made a connection with the database. The memory increases at a time when the page is accessed and not back to normal in no time! the highest peak memory was between 1GB !, then I have to recycle the "pool" in IIS ... I use the methods Connection.Close () and connection.Dispose (), but it seems that they do work. I searched the web more soulção could not find.

Is there any way to solve this problem without having to recycle the pool? Thanks for sharing knowledge !!!

This is the block in which the memory leak occurs:

    SqlConnection cn = new SqlConnection("");
    SqlCommand cm = new SqlCommand();

    SqlDataReader dr = null;

    try
    {
        cn.Open();
        cm.Connection = cn;
        cm.CommandTimeout = 600;
        cm.CommandText = "";

        cm.Parameters.Add("operation", SqlDbType.Int).Value = 1;
        cm.Parameters.Add("now", SqlDbType.DateTime).Value = DateTime.Now;

        dr = cm.ExecuteReader(CommandBehavior.SingleResult);
        while (dr.Read())
        {
            //blah blah blah...
        }
        dr.Close();
    }
    catch (Exception ex)
    {

    }
    finally
    {
        if (dr != null)
            dr.Dispose();

        cm.Dispose();

        cn.Close();
        cn.Dispose();
    }

You are disposing all the disposable object which is good. It would be better to use ' using ' instead of finally in this case. Cannot see any cause for a memory leak by looking at the code you have provided.

using (SqlConnection cn = new SqlConnection(""))
using (SqlCommand cm = new SqlCommand())
{
    .....

     using (var dr = cm.ExecuteReader(CommandBehavior.SingleResult))
     {
        while (dr.Read())
        {
            //blah blah blah...
        }
     }
}

Keep in mind that Garbage Collection doesn't release memory immediately after any instance dispose.

It has been optimized to trigger and release memory only when there is a memory stress. So, if you want to test for memory leaks you should execute Garbage Collection manually before you take memory usage readings.

GC.Collect();
GC.WaitForPendingFinalizers();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM