Collection Modified exception when saving isolated storage settings in windows phone 8 application

197 views Asked by At

This is my code for saving settings in isolated storage.

  public bool AddOrUpdateValue(string Key, Object value)
    {
        bool valueChanged = false;

        // If the key exists
        if (settings.Contains(Key))
        {
            // If the value has changed
            if (settings[Key] != value)
            {
                // Store the new value
                settings[Key] = value;
                valueChanged = true;
            }
        }
        // Otherwise create the key.
        else
        {
            settings.Add(Key, value);
            valueChanged = true;
        }
        return valueChanged;
    }

 public void SaveCurrentTime()
    {

        if (AddOrUpdateValue("DeactivateTime", DateTimeOffset.Now))
        {
            settings.Save();
        }
    }

But sometimes I am getting collection modified exception.Find below exception details

[Type]:[InvalidOperationException] [ExceptionMessage]:[Collection was modified; enumeration operation may not execute.] [StackTrace]:[ at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource) at System.Collections.Generic.Dictionary`2.Enumerator.MoveNext() at WriteArrayOfKeyValueOfstringanyTypeToXml(XmlWriterDelegator , Object , XmlObjectSerializerWriteContext , CollectionDataContract ) at System.Runtime.Serialization.CollectionDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle) at System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) at System.Runtime.Serialization.DataContractSerializer.InternalWriteObject(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) at System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) at System.Runtime.Serialization.XmlObjectSerializer.WriteObject(XmlDictionaryWriter writer, Object graph) at System.Runtime.Serialization.XmlObjectSerializer.WriteObject(Stream stream, Object graph) at System.IO.IsolatedStorage.IsolatedStorageSettings.Save()

Can anyone tell me where it is going wrong?

0

There are 0 answers