This is partly 'for the record' and partly a query about whether the
following is a bug somewhere in .Net (whether it be the CLR, JITter, C#
compiler). This is all in the context of .Net 1.1 SP1.
Recently we (my fellow team members & I) observed an
InvalidOperatio nException - 'collection has been modified', however it
wasn't immediately obvious why this would be occuring. There are no
modifications occuring within the loop and there is not another thread
that could be making a change.
The object being looped over was derived from CollectionBase and the
culprit turned out to be a finalizer on the class, a finalizer that
called Clear() thus modifying the collection. My question then is, why
did the finalizer get called while the CollectionBase object was still
in scope? Or more to the point, the object has clearly gone out of
scope and so should it have done?
Here's some code to demonstrate the issue fairly reliably (on my PC)...
---------------------------------------------
// Our problematic CollectionBase class.
public class TestCollection : CollectionBase
{
public void Add(object o)
{
List.Add(o);
}
~TestCollection ()
{
this.Clear();
}
}
// A helper class. This has no real relevance to the problem.
public class ListItem
{
private string itemCode;
private string itemDescription ;
public ListItem(string itemCode, string itemDescription )
{
this.itemCode = itemCode;
this.itemDescri ption = itemDescription ;
}
public override string ToString()
{
return itemDescription ;
}
}
---------------------------------------------
If you then create a form in Visual Studio, drop a ComboBox and a
button on there and add the following code:
--------------------------------------------
// Creates an instance of TestCollection with some ListItems(see above)
in it.
private TestCollection BuildCol(int size)
{
TestCollection oList = new TestCollection( );
for(int i=0; i<size; i++)
{
string s = i.ToString();
oList.Add(new ListItem(s,s));
}
return oList;
}
// Populates our combobox.
private void PopulateCombobo x()
{
TestCollection col = BuildCol(1000);
foreach(object o in col) // exception thrown here!
{
comboBox1.Items .Add(o);
}
comboBox1.Sorte d = true;
}
// From the button click event we populate the combobox several times
over to
// increase the chances of reproducing the problem.
private void button1_Click(o bject sender, System.EventArg s e)
{
for(int i=0; i<100; i++)
{
PopulateCombobo x();
comboBox1.Items .Clear();
}
}
--------------------------------------------
Running this code generates an exception on every clicks of the button
here. If you don;t get this then you can add a call to GC.Collect()
within the foreach loop to cause a garbage collection which in turn
will invoke the TestCollection' s finalizer.
What I think is happening here is that foreach is just shorthand for
something like:
--------------
IEnumerator e = col.GetEnumerat or();
while(e.Current !=null)
{
// Do stuff here.
e.MoveNext();
}
--------------
So although technically 'col' is in scope for the lifetime of the loop,
in reality a code optimizer may be flagging it as out of scope since it
is not actually being used within the loop. If a garbage collection
happens to occur then the finalizer is called, modifying the collection
and bang! Of course the IEnumerator would normally have a reference to
the collection so this really doesn't seem right to me.
Any thoughts?
Colin Green 2 3195
<bu*******@hotm ail.com> wrote: This is partly 'for the record' and partly a query about whether the following is a bug somewhere in .Net (whether it be the CLR, JITter, C# compiler). This is all in the context of .Net 1.1 SP1.
Recently we (my fellow team members & I) observed an InvalidOperatio nException - 'collection has been modified', however it wasn't immediately obvious why this would be occuring. There are no modifications occuring within the loop and there is not another thread that could be making a change.
The object being looped over was derived from CollectionBase and the culprit turned out to be a finalizer on the class, a finalizer that called Clear() thus modifying the collection.
Did you really need the finalizer in the first place? Very, very few
classes really need finalizers.
My question then is, why did the finalizer get called while the CollectionBase object was still in scope? Or more to the point, the object has clearly gone out of scope and so should it have done?
Let's be clear about things:
1) Objects don't have scope
2) Variables have scope
3) Scope *in itself* doesn't entirely govern whether or not a variable
prevents the object it refers to from being garbage collected
<snip>
Variables don't prevent an object from being garbage collected when the
JIT can tell that the variable's value isn't used again. For instance,
if you do:
object o = new object();
Thread.Sleep(10 00); // During this sleep, the first object is eligible
// for garbage collection
o = new object();
What I think is happening here is that foreach is just shorthand for something like:
-------------- IEnumerator e = col.GetEnumerat or(); while(e.Current !=null) { // Do stuff here.
e.MoveNext(); } --------------
Indeed.
So although technically 'col' is in scope for the lifetime of the loop, in reality a code optimizer may be flagging it as out of scope since it is not actually being used within the loop. If a garbage collection happens to occur then the finalizer is called, modifying the collection and bang! Of course the IEnumerator would normally have a reference to the collection so this really doesn't seem right to me.
In the case of CollectionBase, however, the enumerator doesn't need to
have a reference to the CollectionBase itself - just the "inner list"
it contains.
So, your CollectionBase was genuinely being finalized, although the
"inner list" it used was still in use. Unfortunately, your rogue
finalizer cleared the list, hence the exception you saw.
--
Jon Skeet - <sk***@pobox.co m> http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Hi Jon,
Thanks for the clarification. There was an air of mystery surrounding
this bug for a while so it's nice to fully understand what is going on.
It's worth noting that at least one other person here working on a
seperate project had also come across the same issue and had just
marked it as a bug in dotnet, using workarounds to solve the problem
such as lock statements, GC.KeepAlive() and avoiding the foreach
statement. This makes me wonder if there are others out there that have
made the same assumption and who now just avoid using foreach.
Cheers,
Colin Green This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Gordon Rundle |
last post by:
It drives me nuts that I can't use foreach with an enumerator
instance. I would like the following to be functionally identical:
foreach (Object o in MyCollection) ...
foreach (Object o in MyCollection.GetEnumerator()) ...
For enumerable types that are under my control, is there any reason
not to create an enumerator type that itself implements IEnumerable?
Like so:
class MyEnumerator : IEnumerable, IEnumerator {
|
by: Maziar Aflatoun |
last post by:
Hi everyone,
I'm having a problem with reading user groups on Active Directory using C#.
It returns all the groups in the Universal scope for a specific user.
However, I only need the groups in Global scope and Domain local scope. Does
anyone know I can modify the following code to this?
DirectoryEntry entry = new DirectoryEntry("LDAP://" + Domain, CurrentUser,
pwd, AuthenticationTypes.Secure);
DirectorySearcher mySearcher = new...
|
by: jcc |
last post by:
Hi guys,
I'm a newbie to C#. My Visual Studio 2005 failed to compile the
following code with error as
'HelloWorld.A' does not implement interface member
'System.Collections.IEnumerable.GetEnumerator()'.
'HelloWorld.A.GetEnumerator()' is either static, not public, or has the
wrong return type.
class A : IEnumerable<string>
|
by: Tin Gherdanarra |
last post by:
Dear mpdls,
here is a simple example of an IEnumerable that
generates integers:
It works, but I have only a vague idea of what's
going on. I understand that /yield/ wraps the
humble integer that comes from
counter++
|
by: strawberry |
last post by:
In the function below, I'd like to extend the scope of the $table
variable such that, once assigned it would become available to other
parts of the function. I thought 'global $table;' would solve this but
it's clear that I'm misunderstanding $variable persistence. I posted a
similar enquiry over at alt.php.mysql, but I guess this is a more
appropriate forum because the problems I'm having relate to PHP.
Any help appreciated.
...
| |
by: =?Utf-8?B?a2VubmV0aEBub3NwYW0ubm9zcGFt?= |
last post by:
When creating multiple iterators, the original is defined as returning
IEnumerator, ie
public IEnumerator GetEnumerator() { yield x; ...}
whereas the additional ones are defined as returning IEnumerable, ie
public IEnumerable AnotherSortOrder() { yield x;....}
Any insights out there as to why the additional iteration methods did not
just return IEnumerator?
(its just a little confusing, hoping for some better insight)
|
by: timor.super |
last post by:
Hi group,
imagine I want to count the number of a word in a text. See my actual
code (don't pay attention to the int factor) :
List<KeyValuePair<string, int>listThingsToFind = new
List<KeyValuePair<string, int>>();
listThingsToFind.Add(new KeyValuePair<string, int>("error", 10));
listThingsToFind.Add(new KeyValuePair<string, int>("value", 50));
MyCSharp2Class myClass = new MyCSharp2Class(listThingsToFind, data);
|
by: Ronald S. Cook |
last post by:
Does anyone know how to convert an object of type IEnumerable to a
DataTable?
Thanks,
Ron
|
by: jmDesktop |
last post by:
In the code below from MSDN
How do the PeopleEnum methods ever get called?
foreach (Person p in peopleList)
Console.WriteLine(p.firstName + " " + p.lastName);
What is going on behind the scenes in the foreach?
Also, I could not find where the interface signatures were for the
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |