Using cancellation tokens¶

Hangfire provides support for cancellation tokens for your jobs to let them know when a shutdown request was initiated, or job performance was aborted. In the former case the job will be automatically put back to the beginning of its queue, allowing Hangfire to process it after restart.

Cancellation tokens are exposed through the IJobCancellationToken interface. It contains the ThrowIfCancellationRequested method that throws the OperationCanceledException when cancellation was requested:

  1. public void LongRunningMethod(IJobCancellationToken cancellationToken)
  2. {
  3. for (var i = 0; i < Int32.MaxValue; i++)
  4. {
  5. cancellationToken.ThrowIfCancellationRequested();
  6.  
  7. Thread.Sleep(TimeSpan.FromSeconds(1));
  8. }
  9. }

When you want to enqueue such method call as a background job, you can pass the null value as an argument for the token parameter, or use the JobCancellationToken.Null property to tell code readers that you are doing things right:

  1. BackgroundJob.Enqueue(() => LongRunningMethod(JobCancellationToken.Null));

The implementation is resolved automatically

Hangfire takes care of passing a proper non-null instance of IJobCancellationToken during the job execution at runtime.

You should use cancellation tokens as much as possible – they greatly lower the application shutdown time and the risk of the appearance of the ThreadAbortException.

原文:

http://docs.hangfire.io/en/latest/background-methods/using-cancellation-tokens.html