lbugnion / mvvmlight

The main purpose of the toolkit is to accelerate the creation and development of MVVM applications in Xamarin.Android, Xamarin.iOS, Xamarin.Forms, Windows 10 UWP, Windows Presentation Foundation (WPF), Silverlight, Windows Phone.
http://www.mvvmlight.net
MIT License
1.16k stars 312 forks source link

Intermittent 'enumeration modified' exception in SendToTargetOrType() #109

Open NickHarmer opened 2 years ago

NickHarmer commented 2 years ago

I am seeing very occasional 'enumeration is modified' exceptions when calling Messenger.Send(), as follows:

System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
   at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
   at System.Collections.Generic.Dictionary`2.KeyCollection.Enumerator.MoveNext()
   at System.Linq.Enumerable.<TakeIterator>d__25`1.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at GalaSoft.MvvmLight.Messaging.Messenger.SendToTargetOrType[TMessage](TMessage message, Type messageTargetType, Object token) in C:\Users\lbugn\Documents\MVVMLight\GalaSoft.MvvmLight\GalaSoft.MvvmLight (PCL)\Messaging\Messenger.cs:line 671
   at GalaSoft.MvvmLight.Messaging.Messenger.Send[TMessage](TMessage message) in C:\Users\lbugn\Documents\MVVMLight\GalaSoft.MvvmLight\GalaSoft.MvvmLight (PCL)\Messaging\Messenger.cs:line 296

Looking at the source code I note that there is a lock around this use of the _recipientsOfSubclassesAction dictionary:

lock (_recipientsOfSubclassesAction)
{
    list = _recipientsOfSubclassesAction[type].Take(_recipientsOfSubclassesAction[type].Count()).ToList();
}

but not around this one:

// Clone to protect from people registering in a "receive message" method
// Correction Messaging BL0008.002
var listClone =
                    _recipientsOfSubclassesAction.Keys.Take(_recipientsOfSubclassesAction.Count()).ToList();

which seems to be the source of the error (line 671)

Should this be updated?

michael-hawker commented 2 years ago

@NickHarmer this library is no longer maintained as per the readme:

image

@lbugnion did you plan to archive the repo too?