Last active
March 25, 2023 03:51
-
-
Save emoacht/ab2a03f42cd535ee65288ab2d2a1e3e4 to your computer and use it in GitHub Desktop.
Generate and consume IAsyncEnumerable<T>.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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