Skip to content

Commit eef4d0a

Browse files
committed
Fixed an index exception in Messenger.Send
1 parent c45bb99 commit eef4d0a

File tree

1 file changed

+8
-7
lines changed

1 file changed

+8
-7
lines changed

Microsoft.Toolkit.Mvvm/Messaging/Messenger.cs

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
using System.Buffers;
77
using System.Collections.Generic;
88
using System.Runtime.CompilerServices;
9-
using System.Runtime.InteropServices;
109
using System.Threading;
1110
using Microsoft.Collections.Extensions;
1211

@@ -404,17 +403,19 @@ public unsafe TMessage Send<TMessage, TToken>(TMessage message, TToken token)
404403
lock (this.recipientsMap)
405404
{
406405
// Check whether there are any registered recipients
407-
if (!TryGetMapping(out Mapping<TMessage, TToken>? mapping))
408-
{
409-
return message;
410-
}
406+
_ = TryGetMapping(out Mapping<TMessage, TToken>? mapping);
411407

412408
// We need to make a local copy of the currently registered handlers,
413409
// since users might try to unregister (or register) new handlers from
414410
// inside one of the currently existing handlers. We can use memory pooling
415411
// to reuse arrays, to minimize the average memory usage. In practice,
416412
// we usually just need to pay the small overhead of copying the items.
417-
int totalHandlersCount = mapping!.TotalHandlersCount;
413+
int totalHandlersCount = mapping?.TotalHandlersCount ?? 0;
414+
415+
if (totalHandlersCount == 0)
416+
{
417+
return message;
418+
}
418419

419420
handlers = ArrayPool<object>.Shared.Rent(totalHandlersCount);
420421
recipients = ArrayPool<object>.Shared.Rent(totalHandlersCount);
@@ -428,7 +429,7 @@ public unsafe TMessage Send<TMessage, TToken>(TMessage message, TToken token)
428429
// handlers for different tokens. We can reuse the same variable
429430
// to count the number of matching handlers to invoke later on.
430431
// This will be the array slice with valid actions in the rented buffer.
431-
var mappingEnumerator = mapping.GetEnumerator();
432+
var mappingEnumerator = mapping!.GetEnumerator();
432433

433434
// Explicit enumerator usage here as we're using a custom one
434435
// that doesn't expose the single standard Current property.

0 commit comments

Comments
 (0)