I found a great way on how to do periodic work using the async/await pattern over here: https://stackoverflow.com/a/14297203/899260
Now what I'd like to do is to create an extension method so that I can do
someInstruction.DoPeriodic(TimeSpan.FromSeconds(5));
Is that possible at all, and if, how would you do it?
EDIT:
So far, I refactored the code from the URL above into an extension method, but I don't know how to proceed from there
public static class ExtensionMethods {
public static async Task<T> DoPeriodic<T>(this Task<T> task, CancellationToken token, TimeSpan dueTime, TimeSpan interval) {
// Initial wait time before we begin the periodic loop.
if (dueTime > TimeSpan.Zero)
await Task.Delay(dueTime, token);
// Repeat this loop until cancelled.
while (!token.IsCancellationRequested) {
// Wait to repeat again.
if (interval > TimeSpan.Zero)
await Task.Delay(interval, token);
}
}
}