Last active
February 11, 2023 20:22
-
-
Save brianmed/484fb921e2fcc8a919685cd2d5a9fd2f to your computer and use it in GitHub Desktop.
C# Repeat Slow Task
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
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