1

我在单音中分析下面的代码,发现很多 Rate 对象都保存在内存中,尽管我清除了它们。

protected void FetchingRates()
{
  int count = 0;

  while (true)
  {
    try
    {
      if (m_RatesQueue.Count > 0)
      {
        List<RateLog> temp = null;

        lock (m_RatesQueue)
        {
          temp = new List<RateLog>();
          temp.AddRange(m_RatesQueue);
          m_RatesQueue.Clear();
        }

        foreach (RateLog item in temp)
        {
          m_ConnectionDataAccess.InsertRateLog(item);
        }

        temp.Clear();
        temp = null;
      }
      count++;
      Thread.Sleep(int.Parse(ConfigurationManager.AppSettings["RatesIntreval"].ToString()));
    }
    catch (Exception ex)
    {                   
    }
  }
} 

通过以下方式插入队列:

public void InsertLogRecord(RateLog msg)
{
  try
  {
    if (m_RatesQueue != null)
    {
      //lock (((ICollection)m_queue).SyncRoot)
      lock (m_RatesQueue)
      {
        //insert new job to the line and release the thread to continue working.
        m_RatesQueue.Add(msg);
      }
    }
  }
  catch (Exception ex)
  {
  }
}

工作人员将速率日志插入数据库,如下所示:

 internal int InsertRateLog(RateLog item)
    {
        try
        {
            SqlCommand dbc = GetStoredProcCommand("InsertRateMonitoring");
            if (dbc == null)
                return 0;
            dbc.Parameters.Add(new SqlParameter("@HostName", item.HostName));
            dbc.Parameters.Add(new SqlParameter("@RateType", item.RateType));
            dbc.Parameters.Add(new SqlParameter("@LastUpdated", item.LastUpdated));
            return ExecuteNonQuery(dbc);
        }
        catch (Exception ex)
        {
            return 0;
        }
    }

有人看到可能的内存泄漏吗?

4

4 回答 4

3

停止吞咽所有异常将是我建议的第一个开始。

于 2010-09-02T06:49:25.790 回答
2

您肯定正在清除队列和临时列表(这是不必要的,因为即使在您分配给参考temp之前它也有资格收集)。在这一点上,我认为您的问题更可能与以下行有关。null

m_ConnectionDataAccess.InsertRateLog(item);

您正在将对 a 的引用传递RateLog给另一个方法。您没有提供有关此方法的任何详细信息,因此我无法消除它将自己的引用副本存储在单独的数据结构中的可能性。

于 2010-09-02T14:10:23.097 回答
1

不需要清除和归零List<RateLog> temp. 无论如何它都会被 GC 收集,因为离开函数范围时缺少引用,即在函数结束时没有更多对该变量的引用,因此它将被收集。

于 2010-09-02T14:13:00.440 回答
1

我遇到过同样的问题。这可能有一个真正的解释,但我找不到它。

我假设因为我处于while(true)循环中,所以 GC 不会运行。我不知道这是否是 MS 实现 .NET 框架(.NET 3.5)的产物,但这是我所经历的。

我减轻内存堆积的方法是放在GC.Collect();循环的底部。

我有一种感觉,这与未处理的SqlConnection对象有关。

于 2010-09-04T09:17:17.770 回答