I am trying to make a simple program to learn how to use cancellation tokens, but they seem to be giving me plenty of problems. By adjusting the CancelAfter
value, I can absolutely stop a task dead, but IsCancellationRequested
is not ever calling for me. Since CancelAfter
seems to be executing properly, it's very confusing to me that IsCancellationRequested
fails 100% of the time.
Here's the code: (note, it's a stripped down example)
The function that initializes the task:
void IPCheck() {
var cToken = new CancellationTokenSource();
cToken.CancelAfter(1000);
string tempIP = "123.123.123.123";
Task.Factory.StartNew(() => PingTask(tempIP, cToken.Token), cToken.Token);
}
The task that is successfully(?) canceled, but doesn't have IsCancellationRequested
called.
void PingTask(string addressString, CancellationToken cancelToken) {
Ping currentPing = new Ping();
PingReply replyPing;
replyPing = currentPing.Send(addressString);
string returnString = "Return String Unmodified." + Environment.NewLine;
if (replyPing.Status == IPStatus.Success) {
returnString = "Ping to " + addressString + " successful." + Environment.NewLine);
}
else if (replyPing.Status == IPStatus.TimedOut) {
returnString = "Ping to " + addressString + "timed out." + Environment.NewLine);
}
if (cancelToken.IsCancellationRequested) {
returnString = "Cancellation Requested for " + addressString + Environment.NewLine);
}
TaskHelperReturnString(returnString);
return;
}
Unless it succeeds or times out, while CancelAfter
is set to something like 10000
, returnString
always writes "Return String Unmodified."
A successful ping will be over in an instant. With CancelAfter(1000)
there isn't enough time for it to timeout and nothing is printed, including TaskHelperReturnString()
.
The IP I used always fails, so it's good for testing.