Skip to main content

Background Operations

Async Method with Cleanup

Asynchronous long running operations that can be considered as side effect of service. Activities are running in parallel with services but they can't affect state machine state.

You can use activities to execute any not so necessary operation that is not affecting the application flow. For example UI update loop.

State can run multiple activities at the same time. Notice, the second argument of WithActivity method has a cleanup action. The cleanup action is executed when state has exited and before new state has started.

State state1 = new State("myState")
.WithActivity(async () => {
// do some long running operation in async mode
while(!isReady)
{
await updateUI();
}
}, () => {
// cleanup code, here you can clean all activity resources.
isReady = true;
});

Async Service as an Activity

In case you can't use the above described way, you can use async service as an activity, if you set onDoneand onError target state IDs as null and exit the service when it is cancelled.

State state1 = new State("myState")
.WithInvoke(async (callback) => {
// execute a proper service code here
// once done, emit event to go to next state
await callback("STATE_IS_DONE");
})
.WithTransition("STATE_IS_DONE", "nextState")
// register service without onDone and onError target state ID
// this service can run any long running operation but once it is done
// it will not trigger a transition
.WithInvoke(async (cancel) => {
while(!cancel.IsCancellationRequested)
{
// do wome work untill the service is cancelled
await Task.Delay(1000);
}
}, null, null);