@@ -680,8 +680,7 @@ private async Task BroadcastEventsAsync()
680680 {
681681 // Read until the channel is completed (not until cancelled)
682682 // This ensures all pending events are broadcast during graceful shutdown
683- // Note: ReadAllAsync() completes gracefully when the channel writer is completed,
684- // so no try-catch is needed for normal operation
683+ // Note: ReadAllAsync() completes gracefully when the channel writer is completed
685684 await foreach ( LeadershipChangedEventArgs eventArgs in broadcastChannel . Reader . ReadAllAsync ( ) . ConfigureAwait ( false ) )
686685 {
687686 // Broadcast to all subscriber channels
@@ -705,8 +704,17 @@ private async Task BroadcastEventsAsync()
705704 /// An async enumerable that yields leadership change events as they occur.
706705 /// The enumeration will continue until the service is disposed or the cancellation token is triggered.
707706 /// </returns>
708- public async IAsyncEnumerable < LeadershipChangedEventArgs > GetLeadershipChangesAsync (
709- [ EnumeratorCancellation ] CancellationToken cancellationToken = default )
707+ public IAsyncEnumerable < LeadershipChangedEventArgs > GetLeadershipChangesAsync (
708+ CancellationToken cancellationToken = default )
709+ => GetLeadershipChangesAsyncCore ( cancellationToken , subscriberRegistered : null ) ;
710+
711+ /// <summary>
712+ /// Internal overload that signals when the subscriber is registered.
713+ /// Used by tests to avoid race conditions.
714+ /// </summary>
715+ internal async IAsyncEnumerable < LeadershipChangedEventArgs > GetLeadershipChangesAsyncCore (
716+ [ EnumeratorCancellation ] CancellationToken cancellationToken ,
717+ TaskCompletionSource ? subscriberRegistered )
710718 {
711719 ThrowIfDisposed ( ) ;
712720
@@ -723,6 +731,9 @@ public async IAsyncEnumerable<LeadershipChangedEventArgs> GetLeadershipChangesAs
723731 subscriberChannels . Add ( subscriberChannel ) ;
724732 }
725733
734+ // Signal that the subscriber is now registered
735+ subscriberRegistered ? . TrySetResult ( ) ;
736+
726737 try
727738 {
728739 // Read from the subscriber channel
0 commit comments