Reputation: 215
In the CheckForCancellationAsync function, I only check whether the Job is canceled or not. If it is canceled, I give an error with ThrowIfCancellationRequested() and stop the process.
For this, I check the Job's working method and Cancellation control method with Task.WhenAny.
In Task.WhenAny, the CheckForCancellationAsync function terminates the Task.WhenAny process after the job is canceled. However, the Job's method continues to work.
Why doesn't Task.WhenAny terminate all processes? I don't want to add checks like ThrowIfCancellationRequested() between the codes in the Job's method. How can I terminate the processes with a central control like Task.WhenAny?
Why does a function in Task.WhenAny continue to run when the other function receives an error? How can I stop it from running?
using Hangfire;
using System;
using System.Threading;
using System.Threading.Tasks;
public class JobRunner
{
public static async Task RunAsync(Func<CancellationToken, Task> job, IJobCancellationToken jobCancellationToken)
{
using (var cts = new CancellationTokenSource())
{
var cancellationToken = cts.Token;
var cancellationTask = jobCancellationToken.CheckForCancellationAsync(cancellationToken);
try
{
var jobTask = job(cancellationToken);
var completedTask = await Task.WhenAny(jobTask, cancellationTask);
if (completedTask == cancellationTask)
{
// If the cancellation task completed first, cancel the job task
cts.Cancel();
jobCancellationToken.ThrowIfCancellationRequested();
cancellationToken.ThrowIfCancellationRequested();
}
await jobTask; // Ensure the job completes if it wasn't cancelled
}
catch (OperationCanceledException)
{
Console.WriteLine("Job was cancelled.");
}
}
}
}
Upvotes: 0
Views: 55