Skip to content

MessageHandlers not called anymore by WeakReferenceMessenger after UnregisterAll #4081

@steinhilber

Description

@steinhilber

Describe the bug

The attached message handlers of a WeakReferenceMessenger do not get called anymore correctly for all registered objects after unregistering one of them.

There seems to be an issue with the enumerator of the ConditionalWeakTable. The linked list nodes are not iterated correctly when a key gets removed while enumerating. In this case the "Next"-property of the node is set to null and the while loop stops immediately (without checking the remaining nodes).

Steps to Reproduce

  • Register two recipients to a WeakReferenceMessenger.
  • Call UnregisterAll for the second recipient
  • Handlers for the first recipient will not be called by Send 💥

For more details please see the following failing unit test:

[TestCategory("Mvvm")]
[TestMethod]
[DataRow(typeof(StrongReferenceMessenger))]
[DataRow(typeof(WeakReferenceMessenger))]
public void Test_Messenger_RegisterMultiple_UnregisterSingle(Type type)
{
	var messenger = (IMessenger)Activator.CreateInstance(type);

	var recipient1 = new object();
	var recipient2 = new object();

	int handlerCalledCount = 0;

	messenger.Register<object, MessageA>(recipient1, (r, m) => { handlerCalledCount++; });
	messenger.Register<object, MessageA>(recipient2, (r, m) => { handlerCalledCount++; });

	messenger.UnregisterAll(recipient2);

	messenger.Send(new MessageA());

	Assert.AreEqual(1, handlerCalledCount);
}

Expected behavior

  • The attached message handlers get executed for all registered objects.
  • The unit test above does not fail

Environment

NuGet Package(s):
Microsoft.Toolkit.MVVM

Package Version(s):
7.0.1

Windows 10 Build Number:
- [ ] Fall Creators Update (16299)
- [ ] April 2018 Update (17134)
- [ ] October 2018 Update (17763)
- [ ] May 2019 Update (18362)
- [x] May 2020 Update (19041)
- [ ] Insider Build (build number: )

App min and target version:
- [ ] Fall Creators Update (16299)
- [ ] April 2018 Update (17134)
- [ ] October 2018 Update (17763)
- [ ] May 2019 Update (18362)
- [x] May 2020 Update (19041)
- [ ] Insider Build (xxxxx)

Device form factor:
- [x] Desktop
- [ ] Xbox
- [ ] Surface Hub
- [ ] IoT

Visual Studio
- [ ] 2017 (version: )
- [x] 2019 (version: 16.9.0)
- [ ] 2019 Preview (version: )

Metadata

Metadata

Assignees

No one assigned

    Labels

    .NETComponents which are .NET based (non UWP specific)Completed 🔥bug 🐛An unexpected issue that highlights incorrect behaviormvvm-toolkit 🧰Issues/PRs for the Microsoft.Toolkit.Mvvm package

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions