Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix register/unregister issues of WeakReferenceMessenger #4082

Merged
5 commits merged into from
Jul 5, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion Microsoft.Toolkit.Mvvm/Messaging/WeakReferenceMessenger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,8 @@ public bool MoveNext()

while (node is not null)
{
LinkedListNode<WeakReference<TKey>>? nextNode = node.Next;

// Get the key and value for the current node
if (node.Value.TryGetTarget(out TKey? target) &&
this.owner.table.TryGetValue(target!, out TValue? value))
Expand All @@ -421,7 +423,7 @@ public bool MoveNext()
this.owner.keys.Remove(node);
}

node = node.Next;
node = nextNode;
}

return false;
Expand Down
23 changes: 23 additions & 0 deletions UnitTests/UnitTests.Shared/Mvvm/Test_Messenger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -511,6 +511,29 @@ void Test()
messenger.Cleanup();
}

[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);
}

public sealed class RecipientWithNoMessages
{
public int Number { get; set; }
Expand Down