Skip to content

Instantly share code, notes, and snippets.

@emoacht
Last active March 25, 2023 03:51
Show Gist options
  • Save emoacht/ab2a03f42cd535ee65288ab2d2a1e3e4 to your computer and use it in GitHub Desktop.
Save emoacht/ab2a03f42cd535ee65288ab2d2a1e3e4 to your computer and use it in GitHub Desktop.
Generate and consume IAsyncEnumerable<T>.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Loaded += OnLoaded;
}
private async void OnLoaded(object sender, RoutedEventArgs e)
{
await foreach (var i in GenerateAsync(10))
{
Trace.WriteLine($"Consumed {i}");
if (i >= 5)
break;
}
Trace.WriteLine("Ended");
}
static async IAsyncEnumerable<int> GenerateAsync(int count)
{
for (int i = 0; i < count; i++)
{
await Task.Delay(TimeSpan.FromSeconds(i));
Trace.WriteLine($"Generated {i}");
yield return i;
}
}
static async IAsyncEnumerable<int> GenerateAsync(int count, CancellationToken cancellationToken)
{
for (int i = 0; i < count; i++)
{
await Task.Delay(TimeSpan.FromSeconds(i), cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
Trace.WriteLine($"Generated {i}");
yield return i;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment