The Dangers of Data Binding (part 3456 of infinity)…


So, when you have a form, it’s nice to bind data to the controls. In spite of my personal biases, there is nothing wrong with that.

But, you have to be careful about what you are binding to – if the object that you bind to the control does not go out of scope, the control will not, either. So, you will have a memory leak. The fun thing about this kind of memory leak is it will also leak graphics handles, which are a finite resource on a machine, and so if you have a lot of controls on the form, you may actually crash the application fairly easily, even thought there is memory to spare.

Here is an example of where this kind of data binding problem happened:

   1: uxComboBoxPackageTypes.DataSource = new BindingSource

   2:     (PackageTypeDictionary.PackageTypes, null);

Note that PackageTypeDictionary.PackageTypes is a static dictionary. It will never go out of scope, as long as the application is running. So, in this case, every Med Detail screen that gets popped up in Visual Assign will stay around forever.

The solution, in this case, is to upon form closing, set the DataSource to null, to break the binding:

   1: protected override void OnClosed(EventArgs e)

   2: {

   3:     base.OnClosed(e);




   7:     uxComboBoxPackageTypes.DataSource = null;

   8: }

To find this, I used YourKit (which helped me pin down what was leaking in the overall scheme) and WinDbg (where I got into the gritty details). There are lots of good resources on WinDbg out there, but I want to point out this excellent article which really helped me figure out how to track down event chain leakages (and led to figuring out where the real problem lie):