Background: I have the application which can run algorithms for calculating. Before running an algorithm task, we start an alive task which observes the algorithm is not terminated. If the alive task is terminated, we send a cancellation to the algorithm task and try to stop it via a method which called between code blocks, so we cannot stop the algorithm task immediately.
At the current moment, we use such block of code to check alive task or not:
TaskTokenSource = new CancellationTokenSource();
TaskToken = TaskTokenSource.Token;
IsAliveTokenSource = new CancellationTokenSource();
IsAliveToken = IsAliveTokenSource.Token;
Task.Run(async () =>
{
while (true)
{
var isAlive = TaskAction.GetStatus(TaskId);
Log.Info($"Task status {isAlive.ToDbAttribute()}");
if (isAlive == TaskStatuses.Cancelling)
{
TaskTokenSource.Cancel();
IsAliveTokenSource.Cancel();
}
await Task.Delay(10000);
if(IsAliveToken.IsCancellationRequested)
{
Log.Info($"End heartbeat task {TaskId}");
IsAliveToken.ThrowIfCancellationRequested();
}
}
});
And this method which check the task is terminated between code blocks
public void IsContinue()
{
if (TaskToken.IsCancellationRequested)
TaskToken.ThrowIfCancellationRequested();
}
I try to emulate other logic in console application to generate OperationCanceledException
, but it cannot generate exception like I want. Can you say how to generate OperationCanceledException
immediately, or describe why the logic is not working?
CancellationTokenSource IsAliveTokenSource;
CancellationToken IsAliveToken;
IsAliveTokenSource = new CancellationTokenSource();
IsAliveToken = IsAliveTokenSource.Token;
try
{
//Check the task is alive
Task.Run(async () =>
{
//Placeholder to simulate task terminate
int attempts = 0;
bool isAlive = true;
while (true)
{
//Placeholder generates the task status is not alive
if (attempts == 3)
isAlive = false;
attempts++;
//isAlive = TaskActions.CheckStatus(TaskId);
Console.WriteLine($"Task status: {isAlive}");
if (!isAlive)
IsAliveTokenSource.Cancel();
await Task.Delay(10000);
//Stop checking task status
if (IsAliveToken.IsCancellationRequested)
IsAliveToken.ThrowIfCancellationRequested();
}
});
//Other part of codes
//How to generate OperationCanceledException here ?
Console.ReadLine();
}
catch (OperationCanceledException)
{
Console.WriteLine("Task is terminated");
}
catch (Exception ex)
{
Console.WriteLine(ex);
}