I have an .NET 4.0 assembly; it is registered in GAC and works as part of a BizTalk “orchestration”. Sometimes I get the following error - “Collection was modified; enumeration operation might not execute. : System.InvalidOperationException: Collection was modified; enumeration operation might not execute.”. I cannot reproduce it; when I run the same processing of the same data, my assembly does not generate the error in this place.
The error happens when I call ‘.Where().ToArray()’ for a datatable object: an object of classd System.Data.TypedTableBase.
Here is the code: ..................
int? setTypeGroupId;
...
return instances.WorkContributors.Where
(
c =>
!c.IsInterestedPartyNoNull()
&& c.InterestedPartyNo == publisherIpNo
&& c.SetTypeNo == 1
&& (c.RecordType == "SPU")
&& c.TypeCode == "E"
&& (!setTypeGroupId.HasValue ||
(setTypeGroupId.HasValue && c.SetTypeGroupID == setTypeGroupId))
).ToArray();
..................
The object ‘instances’ is a dataset – my class produced from System.Data.DataSet. The property ‘instances.WorkContributors’ is a datatable: an object of class System.Data.TypedTableBase. The class MyDataRowClass is produced from System.Data.DataRow.
The call stack after the error was the following:
Collection was modified; enumeration operation might not execute. : System.InvalidOperationException: Collection was modified; enumeration operation might not execute.
at System.Data.RBTree1.RBTreeEnumerator.MoveNext()
at System.Linq.Enumerable.<CastIterator>d__97
1.MoveNext()
at System.Linq.Enumerable.WhereEnumerableIterator1.MoveNext()
at System.Linq.Buffer
1..ctor(IEnumerable1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable
1 source)
at MyProduct.FileParser.Types.CWR.PWRType.GetPublishers(CWRWorkInstances instances, Nullable`1 setTypeGroupId)
at MyProduct.FileParser.Validation.Concreate.PwrTypeValidation.ValidatePublisherNumber()
at MyProduct.FileParser.Validation.Concreate.PwrTypeValidation.Validate()
at MyProduct.FileParser.Types.CWR.PWRType.StoreRecord(CWRWorkInstances workInstances, CWRWorkParsingContext context)
at MyProduct.FileParser.Groups.CWR.NWRGroup.StoreGroup(Int32 workBatchID, CWRFileCommonData commonData)
at MyProduct.FileParser.CWRParser.ProcessCWRFile(String fileName, Boolean wait, Boolean deleteFile, String sourceFileName)
I cannot understand why the error happens; and why it happens only sometimes and does not happen on the same processed data again. The error “Collection was modified; enumeration operation might not execute.” Itself is pretty straightforward for me; but I do not see why it happens in that my code. The error is excepted if a code like this:
foreach (DataRow currRow in _someDataTable.Rows)
{
if (/*deletion condition*/)
{
someDataTable.Rows.Remove(currRow);
}
}
But my code above just wants to enumerate System.Data.TypedTableBase and convert the result into an array.
Any ideas?