Jer*_*olz 5 .net c# memory-leaks winforms
如何强制DataGridView释放对绑定DataSet的引用?
我们在DataGridView中显示了一个相当大的数据集,并注意到DataGridView关闭后资源没有被释放.如果用户反复查看此报告,则最终会出现内存不足异常.ANTS Memory Profiler确认DGV尽管dgv.DataSource
设置为null 仍保持引用.
强制 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)
归档时间: |
|
查看次数: |
7695 次 |
最近记录: |