ここで async/await パターンを使用して定期的な作業を行うための優れた方法を見つけました: https://stackoverflow.com/a/14297203/899260
今私がやりたいことは、私ができるように拡張メソッドを作成することです
someInstruction.DoPeriodic(TimeSpan.FromSeconds(5));
それはまったく可能ですか?
編集:
ここまでは、上記のURLのコードを拡張メソッドにリファクタリングしたのですが、そこから先の進め方がわかりません
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);
}
}
}