C#代码中的内存泄漏

时间:2018-08-28 23:10:35

标签: c# memory-leaks

我有一段代码,每分钟都要去数据库一次,以检查是否有任何需要运行的报告,以及是否有运行它的报告。

问题是我对数据库类的对象初始化会导致内存泄漏。如果我看着每次执行代码都打勾的任务mgr“用户对象”增加了5。

private void ReportRunTimer_Tick(object sender, EventArgs e)
        {
            DataConnection dataConnection = new DataConnection(); *<-- when executing this line User Object increasing.*
            try
            {
                reportsToRun = dataConnection.GetListOfTheReportForReportRunTick();
                if (reportsToRun.Count > 0)
                    foreach (string report in reportsToRun)
                    {
                        logs("Starting Automatic report generatin", "Successful");
                        Thread TicketReportMethodThread = new Thread(() => GenerateReport(report, 1));
                        TicketReportMethodThread.Start();
                    }
                dataConnection = null;
            } catch (Exception ex)
            {
                logs("Starting Automatic report generatin failed: " +ex.ToString(), "Error");
            }
            finally
            {
                reportsToRun.Clear();
            }
        }

DataConnection类

public List<string> GetListOfTheReportForReportRunTick()
{
    List<string> RepoerList = new List<string>();
    connString = "Server=xxx;Port=xxx;Database=xxx;Uid=xxx;password=xxxx;SslMode=none";
    using (MySqlConnection mySqlConnection = new MySqlConnection(connString))
    {
        try
        {
            MySqlCommand mySqlCommand = mySqlConnection.CreateCommand();
            mySqlCommand.CommandText = "SELECT reportname FROM reports WHERE nextruntime < NOW()";
            mySqlConnection.Open();
            MySqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();

            while (mySqlDataReader.Read())
            {
                RepoerList.Add(mySqlDataReader["reportname"].ToString());
            }

        }
        catch (MySqlException ex)
        {
            hd.logs("Failed to get reports with reportstorun_tick Error: " + ex.ToString(), "Error");
            mySqlConnection.Close();
        }
        finally
        {
            mySqlConnection.Close();
            mySqlConnection.Dispose();
        }
    }
    return RepoerList;
}

DataConnection dataConnection = new DataConnection();在更多地方使用,这是唯一引起问题的地方。

如果我用下面的公用列表GetListOfTheReportForReportRunTick()中的代码替换私有void ReportRunTimer_Tick中的代码,如下所示。问题不再存在,有什么想法吗?

private void ReportRunTimer_Tick(object sender, EventArgs e)
{
    List<string> reportsToRun = new List<string>();
    try
    {
        connString = "Server=xxx;Port=xxx;Database=xxx;Uid=xxx;password=xxxx;SslMode=none";
        using (MySqlConnection mySqlConnection = new MySqlConnection(connString))
        {
            try
            {
                MySqlCommand mySqlCommand = mySqlConnection.CreateCommand();
                mySqlCommand.CommandText = "SELECT reportname FROM reports WHERE nextruntime < NOW()";
                mySqlConnection.Open();
                MySqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();

                while (mySqlDataReader.Read())
                {
                    reportsToRun.Add(mySqlDataReader["reportname"].ToString());
                }



                if (reportsToRun.Count > 0)
                    foreach (string report in reportsToRun)
                    {
                        logs("Starting Automatic report generatin", "Successful");
                        Thread TicketReportMethodThread = new Thread(() => GenerateReport(report, 1));
                        TicketReportMethodThread.Start();

                    }
            }
            catch (MySqlException ex)
            {
                logs("Failed to get reports with reportstorun_tick Error: " + ex.ToString(), "Error");
                mySqlConnection.Close();
            }
            finally
            {
                mySqlConnection.Close();
                mySqlConnection.Dispose();
            }
        }

    }
    catch (Exception ex)
    {
        logs("Starting Automatic report generatin failed: " + ex.ToString(), "Error");
    }
    finally
    {
        reportsToRun.Clear();

    }

}

问题是由

引起的
DataConnection dataConnection = new DataConnection(); *<-- when executing this line User Object increasing.*
reportsToRun = dataConnection.GetListOfTheReportForReportRunTick();

但是我不明白为什么。

1 个答案:

答案 0 :(得分:3)

我认为内存泄漏是因为您没有处置MySqlDataReader。您可以通过将其包装在如下using语句中来完成此操作:

using(MySqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader()){
    while (mySqlDataReader.Read())
    {
        RepoerList.Add(mySqlDataReader["reportname"].ToString());
    }
}