I am trying to achieve cancel tasks feature in service fabric stateful services.
Plan is using cancellation token to propagate notices to linked threads / Tasks.
CancellationToken
& CancellationTokenSource
are not serializable and doesn't flow across service calls or Data Replication in SF. It can only be used to tell the handler within the same process that an operation has been cancelled and should stop any processing or ignore any continuation in case a response is received.
If you want to be able to start and cancel an operation in another service, you should split the operation in two calls.
CancellationTokenSource
for this operation to generate a CancellationToken
to be passed to the Task\Thread running in the backgroundCancellationTokenSource
exists and cancel it, so that the token provided to any Task\Thread can stop any processing, if not already completed or cancelled.You could simply store it as a Dictionary<Guid, CancellationTokenSource>
in the process\partition running the task.
In case you are running these tasks in multiple partitions in SF, and is planning to store it in a Reliable Dictionary, it is not a good idea, because as said previously, you can't serialize the cancellation to other partitions.
In this case you can store the OperationID and the PartitionID, so all partitions know where an operation is running, when you receive a call for cancellation on any of the partitions, the service will lookup in this reliable dictionary where the operation is running and forward the cancellation to the right partition.