我發現瞭如何使用異步/ 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);
}
}
}
你知道如何創建一個擴展方法嗎?如果是的話,你有答案,如果沒有,你可以使用谷歌。 – 2013-03-18 07:37:51
@MarcinJuraszek我將鏈接中的代碼重構爲擴展方法,但我不知道如何從那裏繼續。看我的編輯。 – lightxx 2013-03-18 07:50:20
顯示您的代碼,然後 – MarcinJuraszek 2013-03-18 07:50:52