Databining in .NET 2.0 and the TADataSource for 1.1 resolved the Memory Leak problems associated with Strong Delegates

In .NET 1.1. and 2.0 you might end up with a UI element not being garbage collected after it is disposed, as it is still attached to a currency manager.

Most solutions presented for this problem however only work for simple data binding.

1. E.g. clearing the controls databindings collection in the dispose method
2. Another try would be to try determine which data object is beeing accessed and free from there using:

event EventHandler evt;Delegate[] thedelegates = evt.GetInvocationList(); foreach (Delegate _d in thedelegates) {evt -= (EventHandler)_d;}

Both solutions do not solve the problem in an easy and realiably way. In tangible architect we introduced a datasource component which has a contextrootobject propery which must be set to null to free up all bindings including complex bindings. It's nice to see that microsoft took a similar approach:

"One of the most appropriate solution to the memory leak problems associated with the databindings in windows forms can be BindingSource

If we consider datagridview and datagrid databindings as example

Each DataGridView/DataGrid bound to a data set needs a CurrencyManager to communicate back and forth w the DataSet. In the context of your app, each of the child forms creates a CurrencyManager. After the child form is closed and disposed, the CurrencyManager is still kept alive

The main reason we can't forcingly throw away CurrencyManager once their form is closed and disposed is because CurrencyManager's can be shared between multiple forms ( sharing currency managers between multiple forms is the easiest way to keep data in sync on these forms ). Destroying the CurrencyManager because one form was closed would mean that other forms will not be updated when data changes.Currently there are applications which use CurrencyManagers between multiple forms. Changing the behavior explained above would break these application. This would break backward compatibility and because of that we can't change the existing behavior.

The workaround for this problem is to have the DataGridView/DataGrid bind to the data set through the new BindingSource component. Then, when the child form is disposed, set the BindingSource::DataSource to null."

Microsoft Beta One Support, Thank you!

For more information on the problem see:

1 comment:

Tim F. Fischer said...

Also see the following MSDN article:

MSDN Article Field Views on data binding

And a variant of this problem is at Gref Schelters Blog:

Simulating Weak Delegate in .NET