C# .NET Framework 1.1 bug in Control class

Hi,

I just encountered something really fishy in the .NET framework.

I am iterating over the Controls (Control.Controls Collection) of a derived control to effect some selection logic. When I iterative over this collection, I sporadically get the same reference twice ie: a foreach statement returns the same control multiple times instead of each individual control once.

This problem seems to be race-conditional as it does not occur if I break during the iteration. A stack trace shows that the iteration is in fact producing the same reference twice.

If I use a hashtable of references to the same objects instead of the Control.Controls collection this problem magically disappears! WOW!

Has anyone else seen this? Any comments from Microsoft land?

Like this...

using System.Collections;

....
public class MyControl : Control
{
IDictionary controls = new Hashtable()

.....
private void AddChildControl(Control child)
{
this.Controls.Add(child); //using the inherited collection
controls[GUID] = child; //using my own collection
}

.....
private void DoSelectionThingy()
{
//THIS DOESN'T WORK!!!!!!!!!
foreach(Control control in Controls)
{
IMyControl myControl = control as IMyControl
if(myControl != null)
{
myControl.Select = true;
}
}

//THIS DOES WORK!!!!!!!!!
foreach(Control control in controls)
{
IMyControl myControl = control as IMyControl
if(myControl != null)
{
myControl.Select = true;
}
}
.....
}

[1581 byte] By [mspence] at [2007-12-16]
# 1

Does all this code run on the same thread?

DavidM.Kean at 2007-9-9 > top of Msdn Tech,Windows Forms,Windows Forms General...
# 2
Hmm, strange. Hard to know how its getting off kilter.

The best way to override the controls collection is to inherit from it and return your custom control collection from CreateControlsInstance.

http://blogs.msdn.com/jfoscoding/articles/450843.aspx

Hope this helps,
Jessica

Jessica at 2007-9-9 > top of Msdn Tech,Windows Forms,Windows Forms General...