Method Publish
| Edit this page View SourcePublish<TSource>(IEnumerable<TSource>)
Creates a buffer with a view over the source sequence, causing each enumerator to obtain access to the remainder of the sequence from the current index in the buffer.
Declaration
public static IBuffer<TSource> Publish<TSource>(this IEnumerable<TSource> source)
Parameters
Type | Name | Description |
---|---|---|
IEnumerable<TSource> | source | Source sequence. |
Returns
Type | Description |
---|---|
IBuffer<TSource> | Buffer enabling each enumerator to retrieve elements from the shared source sequence, starting from the index at the point of obtaining the enumerator. |
Type Parameters
Name | Description |
---|---|
TSource | Source sequence element type. |
Remarks
A separate buffer will be maintained for each IEnumerator<T> created from the returned IEnumerable<T>. This buffer will be maintained until the enumerator is disposed, and will contain
all elements returned by source
from the time that the IEnumerator<T> is
created.
This operator uses deferred execution and streams its result.
Examples
The following code example demonstrates how to publish multiple views of the same enumerator using Publish
.
var sequence = Enumerable.Range(0, 10);
// allow multiple consumers to cache views of the same sequence
using var rng = sequence.Publish();
using var e1 = rng.GetEnumerator(); // e1 has a view on the source starting from element 0
Debug.Assert(e1.MoveNext());
Console.WriteLine("e1.MoveNext()");
Console.WriteLine($"e1.Current: {e1.Current}");
Debug.Assert(e1.MoveNext());
Console.WriteLine("e1.MoveNext()");
Console.WriteLine($"e1.Current: {e1.Current}");
using var e2 = rng.GetEnumerator();
Debug.Assert(e2.MoveNext()); // e2 has a view on the source starting from element 2
Console.WriteLine("e2.MoveNext()");
Console.WriteLine($"e1.Current: {e1.Current}");
Console.WriteLine($"e2.Current: {e2.Current}");
Debug.Assert(e1.MoveNext()); // e1 continues to enumerate over its view
Console.WriteLine("e1.MoveNext()");
Console.WriteLine($"e1.Current: {e1.Current}");
Console.WriteLine($"e2.Current: {e2.Current}");
// This code produces the following output:
// e1.MoveNext()
// e1.Current: 0
// e1.MoveNext()
// e1.Current: 1
// e2.MoveNext()
// e1.Current: 1
// e2.Current: 2
// e1.MoveNext()
// e1.Current: 2
// e2.Current: 2
Exceptions
Type | Condition |
---|---|
ArgumentNullException |
|