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();
- Pass the token returned by the GrainCancellationTokenSource.Token property to each grain method that listens for cancellation.
var waitTask = grain.LongIoWork(tcs.Token, TimeSpan.FromSeconds(10));
- A cancellable grain operation needs to handle the underlying
CancellationToken
property ofGrainCancellationToken
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 theGrainCancellationTokenSource
object.
tcs.Dispose();
Important considerations
- The
GrainCancellationTokenSource.Cancel
method returns aTask
, 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.
Collaborate with us on GitHub
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, see our contributor guide.