store cancellation tokens in service fabric services

半腔热情 提交于 2019-12-01 14:22:29

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.

  • The first will generate an Operation ID to be returned to the client, and Create a CancellationTokenSource for this operation to generate a CancellationToken to be passed to the Task\Thread running in the background
  • The second will receive and OperationID and identify if a CancellationTokenSource 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!