Grain cancellation tokens

The Orleans runtime provides a mechanism called grain cancellation token, that enables the developer to cancel an executing grain operation.

Description

GrainCancellationToken is a wrapper around the standard CancellationToken, which enables cooperative cancellation between threads, thread pool work items, or Task objects, and can be passed as a grain method argument.

A GrainCancellationTokenSource is an object that provides a cancellation token through its Token property and sends a cancellation message by calling its GrainCancellationTokenSource.Cancel method.

Usage

  • Instantiate a CancellationTokenSource object, which manages and sends cancellation notifications to the individual cancellation tokens.
var tcs = new GrainCancellationTokenSource();
var waitTask = grain.LongIoWork(tcs.Token, TimeSpan.FromSeconds(10));
  • A cancellable grain operation needs to handle the underlying CancellationToken property of GrainCancellationToken just like it would do in any other .NET code.
public async Task LongIoWork(GrainCancellationToken tc, TimeSpan delay)
{
    while (!tc.CancellationToken.IsCancellationRequested)
    {
        await IoOperation(tc.CancellationToken);
    }
}
  • Call the GrainCancellationTokenSource.Cancel method to initiate cancellation.
await tcs.Cancel();
  • Call the Dispose method when you are finished with the GrainCancellationTokenSource object.
tcs.Dispose();

Important considerations

  • The GrainCancellationTokenSource.Cancel method returns a Task, and to ensure cancellation the cancel call must be retried in case of transient communication failure.
  • Callbacks registered in underlying System.Threading.CancellationToken are subjects to single-threaded execution guarantees within the grain activation on which they were registered.
  • Each GrainCancellationToken can be passed through multiple methods invocations.