Created
December 21, 2012 20:31
-
-
Save maxfridbe/4355598 to your computer and use it in GitHub Desktop.
periodically run task with cancellation input
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
//original http://stackoverflow.com/a/7472334/518 | |
var cancellationTokenSource = new CancellationTokenSource(); | |
var task = Repeat.Interval( | |
TimeSpan.FromSeconds(15), | |
() => CheckDatabaseForNewReports(), cancellationTokenSource.Token); | |
internal static class Repeat | |
{ | |
public static Task Interval( | |
TimeSpan pollInterval, | |
Action action, | |
CancellationToken token) | |
{ | |
// We don't use Observable.Interval: | |
// If we block, the values start bunching up behind each other. | |
return Task.Factory.StartNew( | |
() => | |
{ | |
for (;;) | |
{ | |
if (token.WaitCancellationRequested(pollInterval)) | |
break; | |
action(); | |
} | |
}, token, TaskCreationOptions.LongRunning, TaskScheduler.Default); | |
} | |
} | |
static class CancellationTokenExtensions | |
{ | |
public static bool WaitCancellationRequested( | |
this CancellationToken token, | |
TimeSpan timeout) | |
{ | |
return token.WaitHandle.WaitOne(timeout); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment