I have a scenario where I would like to dump in-memory data to reliable dictionary when replica is about to lose its primary status.
Would the correct approach be to do it on the RunAsync method by watching the cancellation token? For example:
protected override async Task RunAsync(CancellationToken cancellationToken)
{
while (true)
{
// exit only after data is dumped to reliable dictionary
if (cancellationToken.IsCancellationRequested)
{
await DumpDataToDictionaryAsync(data);
cancellationToken.ThrowIfCancellationRequested();
}
...
If the information should be persisted you should do so whenever it changes. In the case that the service crashes you won't have the ability to save anything. Even in the case of a switch from primary to secondary replica there is no way to save your reliable collections. The documentation about the lifecycle states:
In Service Fabric, when a Primary is demoted, one of the first things that happens is that write access to the underlying state is revoked.
Because there is no way to tell when a replica will lose its primary status either it is impossible to save your data in a a reliable collection.