Skip to content

Commit 1751f8f

Browse files
Improve round-robin algorithm.
1 parent 316b7b8 commit 1751f8f

1 file changed

Lines changed: 10 additions & 0 deletions

File tree

Open.ChannelExtensions/Extensions.Merge.cs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,19 +51,29 @@ public MergingChannelReader(IEnumerable<ChannelReader<T>> sources)
5151

5252
public override bool TryRead(out T item)
5353
{
54+
int previous = -1;
5455
// Try as many times as there are sources before giving up.
5556
for (var attempt = 0; attempt < _count; attempt++)
5657
{
5758
// If the value overflows, it will be negative, which is fine, we'll adapt.
5859
var i = Interlocked.Increment(ref _next) % _count;
5960
if (i < 0) i += _count;
61+
6062
var source = _sources[i];
6163

6264
if (source.TryRead(out T? s))
6365
{
6466
item = s;
6567
return true;
6668
}
69+
70+
// Help the round-robin to try each source at least once.
71+
// If previous is not -1 and i is not the next in the sequence,
72+
// then another thread has already tried that source.
73+
if (previous != -1 && (previous + 1) % _count != i)
74+
attempt--; // Allow for an extra attempt.
75+
76+
previous = i;
6777
}
6878

6979
item = default!;

0 commit comments

Comments
 (0)