Saving state

Actors generally need to persist their internal state so that they can recover it in case an Actor is started or restarted, in case of node crashes, or migrated across nodes in cluster. State persistence is also necessary to build complex Actor workflows that transform and enrich input data and generate resultant data that helps make decisions to carry out further operations.

For example, for an automobile system, a fuel Actor may persist the fuel consumption in its state to later calculate the mileage of the vehicle, which may later help decide whether the vehicle requires a maintenance check.

The Actor base class contains the read only StateManager property that can be used to operate with state data. The following lines of code, can save and retrieve state data where the argument cancellationToken is an object of type CancellationToken:

    //  Save state data 
this.StateManager.TryAddStateAsync("count", 0);
// Read state data
var result = await this.StateManager.GetStateAsync<int>("count",
cancellationToken);

If you want to initialize the state, then you should do so in the OnActivateAsync method. Finally, since Actors are single-threaded, we do not need to add concurrency checks while saving or reading state data. Also, since the state is local to the Actor instance, you don't need to add Actor identifier while preserving the state. What this means is that if an Actor named A preserves something in state then the information won't be visible to another instance of the same Actor named B. The state information can only be operated upon by the Actor named A.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.206.91