Я хотел бы использовать токены отмены, как описано в официальной документации https://docs.hangfire.io/en/latest/background-methods/using-cancellation-tokens.html
Однако после вызова метода путем передачи JobCancellationToken.Null
токен, похоже, немедленно отменяется, потому что * выбрасывается исключение ct.ThrowIfCancellationRequested();
Без логики токена отмены метод долгосрочного запуска работает гладко.
Моя архитектура выглядит следующим образом:
BackgroundService.cs
public class BackgroundService : IBackgroundService
{
private readonly IBackgroundJobClient client;
public BackgroundService(IBackgroundJobClient client)
{
this.client = client ?? throw new ArgumentNullException(nameof(client));
}
public async Task<string> EnqueueTaskAsync(string id)
{
string jobId = client.Enqueue<ITaskService>(x => x.ProcessAsync(id, JobCancellationToken.Null));
await Task.CompletedTask;
return jobId;
}
}
TaskService.cs
public class TaskService : ITaskService
{
private readonly ILogger logger;
private readonly IMediator mediator;
public TaskService(ILoggerFactory loggerFactory, IMediator mediator)
{
this.logger = loggerFactory?.CreateLogger<TaskService>() ?? throw new ArgumentNullException(nameof(loggerFactory));
this.mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
}
public async Task ProcessAsync(string id, IJobCancellationToken ct)
{
var cts = CancellationTokenSource.CreateLinkedTokenSource(ct.ShutdownToken);
cts.Token.Register(() =>
{
Console.WriteLine("Cancelled taskId: " + id + " " + DateTime.Now);
});
ct.ThrowIfCancellationRequested();
// ...
}
}
с использованием Microsoft.Extensions.DependencyInjection
services.AddTransient<ITaskService, TaskService>();
services.AddSingleton<IBackgroundService, BackgroundService>();
Вывод журнала консоли
[12:15:16 WRN] Creating a job based on method `ProcessAsync`...
[12:15:16 WRN] Job `269` state `` was unapplied.
[12:15:16 WRN] Job `269` state was changed from `` to `Enqueued`
[12:15:16 WRN] Job that is based on method `ProcessAsync` has been created with id `269`
[12:15:26 WRN] Job `269` state `Enqueued` was unapplied.
[12:15:26 WRN] Job `269` state was changed from `Enqueued` to `Processing`
[12:15:26 WRN] Starting to perform job `269`
Cancelled taskId: d3c56cc1-3cfb-45d7-bba3-ff486fd4aa99 25/10/2019 12:15:26
[12:15:26 WRN] Job `269` has been performed
Используемые версии
- .NET Core 2.2
- HangFire.Core 1.7.7
- Hangfire. AspNetCore 1.7.7
- Hangfire.LiteDB 0.2.1
Есть предложения, что может вызвать такое поведение?