2
Vote

Can't Subscribe while handling a Published message

description

During publishing a message by the MessageCoordinator the message is received on a receiver and the registered action is executed. During the action a new message will be subscribed. This results in a System.InvalidOperationException: Collection was modified; enumeration operation may not execute.

In our case the new subscription will occur because we generate dynamic new IView controls. On the fly the presentors are created and they subscribe on other messages. We really need it.

Short test for reproduction:
        var mc = new WebFormsMvp.MessageCoordinator();
        int total = 0;
        mc.Subscribe<string>(ms=>mc.Subscribe<int>(mi=>total+=mi));
        mc.Publish("hello world");
Suggested solution:
Simple add a ToArray in the publish method to snapshot the subscription on the start of publication.
code MessageCoordinator.PushMessage:
change the line:

foreach (var action in messageReceivedCallbacks.Keys.Where(k => k.IsAssignableFrom(messageType)).SelectMany(t => (IEnumerable<Action<object>>)messageReceivedCallbacks[t]))

to:

foreach (var action in messageReceivedCallbacks.Keys.Where(k => k.IsAssignableFrom(messageType)).SelectMany(t => (IEnumerable<Action<object>>)messageReceivedCallbacks[t]).ToArray())

Regards,

Frans Harinck

comments