I have a function that makes periodic checks to a web page (using REST) and then waits for a final response, if it gets a "non-final" response it tries again.
void PeriodicallyCheckSomething()
{
Task.Run(() => {
var isTaskComplete = false;
while (!isTaskComplete)
{
CancellationToken.WaitHandle.Wait(5000);
if (isTaskComplete || CancellationToken.IsCancellationRequested)
return;
CheckProgress((isComplete) => {
isTaskComplete = isComplete;
CancellationToken.WaitHandle.Set(); // <== can't do this
});
}
});
}
// CheckProgress - exit's immediately, we use updateStatus to report the result
void CheckProgress(Action<bool> updateStatus)
{
MakeWebRequest((data) => {
var isComplete = (data.Result == 999);
updateStatus(isComplete);
});
}
I would like to exit the task cleanly. When I get a result I set the isTaskComplete flag, but the task is already in the wait state.
I would like to "Set" the Waithandle so that the Task immediately exits. However a CancellationToken.Waithandle doesn't have a Set function.
Is there a better way to Wait... that would support both Task Cancellation and the ability to signal it using something like Set?