DataGridView中的明显内存泄漏

Jer*_*olz 5 .net c# memory-leaks winforms

如何强制DataGridView释放对绑定DataSet的引用?

我们在DataGridView中显示了一个相当大的数据集,并注意到DataGridView关闭后资源没有被释放.如果用户反复查看此报告,则最终会出现内存不足异常.ANTS Memory Profiler确认DGV尽管dgv.DataSource设置为null 仍保持引用.

Jer*_*olz 1

强制 DataGridView 释放资源的技巧是通过中间对象进行绑定BindingSource

代码看起来像这样:

...
DataGridView dgvQueryResults;
DataTable m_dataTable;
BindingSource m_binder;

public void PopulateView()
{
  ...
  // Bind the data source through and intermediary BindingSource
  m_binder.DataSource = m_dataTable;
  dgvQueryResults.DataSource = m_binder;
  ...
}


/// <summary>
/// Frees lindering resources. Sets data bindings to null and forces 
/// garbage collection.
/// </summary>
private void ResetDataGridView()
{
  dgvQueryResults.DataSource = null;

  if (null != m_binder) m_binder.DataSource = null;
  m_binder = null;

  dataTable = null;

  // Force garbage collection since this thing is a resource hog!
  GC.Collect ();

  m_binder = new BindingSource ();
}

...
Run Code Online (Sandbox Code Playgroud)

  • Microsoft 建议使用 BindingSource:http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=92260 在这种情况下,调用 `GC.Collect()` 是必要的,因为用户可以更快地单击报告GC 会释放资源,应用程序很快就会因内存不足异常而崩溃。当然,报告功能可以重写以使其发挥得更好一些。顺便说一句,这整件事的发生是由于经典没有使用实际数据集进行测试的结果 8] (2认同)