I have a Task which is as below :
CancellationTokenSource cts = new CancellationTokenSource();
var token = cts.Token;
var task = Task.Run(() =>
{
do {
Console.log("Check status");
if (cts.IsCancellationRequested)
{
break;
}
Thread.Sleep(5*60*1000);
status = GetStatus();
Console.log("status in while loop : " + status);
if (status == "Complete")
{
flag = 1;
break;
}
} while (flag == 1)
Console.log("status after while: " + status);
// some other businness logic
},token);
if (task.Wait(System.TimeSpan.FromMinutes(1))){
Console.log ("Success");
}
else{
Console.log ("Timed out");
cts.Cancel();
StopExecution();
}
void Stop Execution(){
Console.log ("Stopping Execution");
// logic to stop
Console.log("Stopped Successfully");
}
I have written the above code , to run some task for some time and cancel it when the specified time is up.
The problem with the above code is , when ever there is time out happening , it comes to the else block , but it is not cancelling the task which is running.
So I'll show the execution flow with the help of logs :
CheckStatus
status in while loop : InProgress
CheckStatus
status in while loop : InProgress
Timed out
Stopping Execution
CheckStatus
Stopped Successfully
status after while: InProgress
What I observe is even after task is timed-out , it is still executing the task.
My requirement is once the time is up , it should end the entire task and should not be executed at all. In this example I have shown just the do while logic , but there is some other business logic as well.
I want the entire task execution to be stopped and proceed further. Can anyone point me what am I doing wrong to achieve that?