odinserj/HangFire — pull request #103 by odinserj (2014-05-22 20:52:31+00:00)
Title: Cancellation token

Cancellation token allows a job to implement graceful shutdown points. It provides the `IJobCancellationToken.ThrowIfCancellationRequested` method that throws the `OperationCanceledException` when job performance was canceled due to:

* **Shutdown request** – executed on `BackgroundJobServer.Stop` method invocation. Performed automatically when ASP.NET application is shutting down.
* **State transition** – the state of the job has been changed, and it is not in the `Processing` state. `BackgroundJob.Delete`, `BackgroundJob.Requeue` as well as all Monitor interface buttons lead to the job cancellation (in case it is running).

If a job was canceled due to shutdown event, it is being re-queued automatically, so it will be started again on application restart. If a job was canceled due to state transition (read: aborted), it will be re-queued only when someone change its state to `Enqueued` (or click a `Requeue` button in Monitor).

### Create a cancelable job

```csharp
BackgroundJob.Enqueue(() => Cancelable(1000, JobCancellationToken.Null));
```

### Method implementation

```csharp
public static void Cancelable(int iterationCount, IJobCancellationToken token)
{
try
{
for (var i = 1; i <= iterationCount; i++)
{
Thread.Sleep(1000);
Console.WriteLine("Performing step {0} of {1}...", i, iterationCount);

token.ThrowIfCancellationRequested();
}
}
catch (OperationCanceledException)
{
Console.WriteLine("Cancellation requested, exiting...");
throw;
}
}
```

### Unit testing

```csharp
public void Test()
{
var token = new JobCancellationToken(true);
Cancelable(10, token);
}
```