I have a task that needs to run periodically. My first implementation was like:
public static void CheckTask(CancellationTokenSource tokenSource)
{
do
{
// Do some processing
Console.WriteLine("Processing");
// Sleep awhile and wait for cancellation
// If not cancelled, repeat
} while (!tokenSource.Token.WaitHandle.WaitOne(1500));
Console.WriteLine("Bye bye");
}
This task is started like so:
CancellationTokenSource tokenSource = new CancellationTokenSource();
Task task = null;
task = new Task((x)=> {
CheckTask(tokenSource);
//CheckTask2(t, (object)tokenSource);
}, tokenSource.Token);
task.Start();
Then I thought instead of looping in the task, why not reschedule it using ContinueWith? My next implementation was like this:
public static void CheckTask2(Task task, object objParam)
{
CancellationTokenSource tokenSource = (CancellationTokenSource)objParam;
// Do some processing
Console.WriteLine("Processing");
// Sleep awhile and wait for cancellation
if(tokenSource.Token.WaitHandle.WaitOne(1500))
{
Console.WriteLine("Cancel requested");
return;
}
// Reschedule
task.ContinueWith(CheckTask2, tokenSource);
}
The second implementation is much easier to read and write and my tests showed no difference but I still wonder if there are drawbacks for a task to ContinueWith itself?