Skip to content

Instantly share code, notes, and snippets.

@brianmed
Last active February 11, 2023 20:22
Show Gist options
  • Save brianmed/484fb921e2fcc8a919685cd2d5a9fd2f to your computer and use it in GitHub Desktop.
Save brianmed/484fb921e2fcc8a919685cd2d5a9fd2f to your computer and use it in GitHub Desktop.
C# Repeat Slow Task
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
namespace JoyRepeateTask;
public class Program
{
private static async IAsyncEnumerable<IReadOnlyList<object>> CountUp() {
yield return new object[] { 1 };
await Task.Delay(100);
yield return new object[] { 2 };
await Task.Delay(100);
yield return new object[] { 3 };
await Task.Delay(2000);
yield return new object[] { 4 };
await Task.Delay(100);
yield return new object[] { 5 };
}
private static async IAsyncEnumerable<IReadOnlyList<object>> WithOneSecondRepeats(IAsyncEnumerable<IReadOnlyList<object>> reader) {
var enumerator = reader.GetAsyncEnumerator();
bool hasNext = true;
IReadOnlyList<object> item = null;
Task<bool> moveNextTask = enumerator.MoveNextAsync().AsTask();
while (hasNext) {
await Task.WhenAny(Task.Delay(1000), moveNextTask);
if (item is not null) {
yield return item;
}
if (moveNextTask.IsCompleted) {
hasNext = moveNextTask.Result;
item = enumerator.Current;
moveNextTask = enumerator.MoveNextAsync().AsTask();
}
}
}
public static async Task Main()
{
var reader = CountUp();
reader = WithOneSecondRepeats(reader);
await foreach (var item in reader) {
Console.WriteLine(item[0]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment