Question

I have a SortedDictionary defined:

private SortedDictionary<int, SingleQcCalculation> m_dicTagsToCalc;

And I'm iterating over it and setting a propery inside the value:

foreach (KeyValuePair<int, SingleQcCalculation> pairSingleCalc in m_dicTagsToCalc)
{
    try 
    {                        
        pairSingleCalc.Value.m_QCtoCalc.m_CurGroupID = pairSingleCalc.Value.m_ChangedQcGroupId;
        pairSingleCalc.Value.m_QCtoCalc.CalculateQCExpression(pairSingleCalc.Value.m_OPCChangeTime, pairSingleCalc.Value.m_calcTime);
    }
    catch (Exception ex)
    {
        logger.Error(LogTopicEnum.DA,"Error calculating calced QC (id=" + pairSingleCalc.Value.m_QCtoCalc.ID.ToString() + ")" , ex);
    }
}

And for some reason I get this exception:

DoQCsCalculations: error while calculating calced tags
System.InvalidOperationException: Collection was modified after the enumerator was instantiated.
   at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
   at System.Collections.Generic.SortedSet`1.Enumerator.MoveNext()

Now , I'm not changing the values or the keys in the dictionary, there is no other threads using the dictionary.

Why am I getting this error?

Thanks, Omer

Était-ce utile?

La solution

Mutating a value in the dictionary, in and of itself, will not cause this exception to be thrown. You must be either adding or removing a key pair for that exception to be thrown.

Even if you were mutating a key it wouldn't throw this exception, it would just (potentially) not function properly as it wouldn't be able to find items correctly.

Ideally if the function that you're calling is adding pairs to the dictionary it should instead return those key pairs from the method, and the caller can then store those values and add them after the end of the loop, rather than mutating the dictionary while you're enumerating it.

Autres conseils

simply rather than iterating through the dictionary, iterate through the keys and use the keys as the index to the dictionary.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top