Skip to content

BackgroundTasks: Background task suspension

ronimizy edited this page Jan 29, 2024 · 3 revisions

Samples

Suspend task execution

You can suspend background task execution and proceed it later (ex: waiting for kafka callback, or user interaction through UI)

To suspend task, return suspended result from it's execution, after the task proceeding would be invoked, task will restart. You should store some task state in execution metadata, as it will be saved after task in suspended, and task will be executed with this metadata when it is proceeded.

public async Task<BackgroundTaskExecutionResult<EmptyExecutionResult, EmptyError>> ExecuteAsync(
        BackgroundTaskExecutionContext<EmptyMetadata, EmptyExecutionMetadata> executionContext,
        CancellationToken cancellationToken)
{
    ...
    
    if (...)
    {
        ...

        return BackgroundTaskExecutionResult.Suspended.ForEmptyResult().ForEmptyError();   
    }
    
    ...
}

Proceed task execution

To proceed task execution, use IBackgroundTaskRunner's ProceedBackgroundTask builder property.
You have to configure builder with task search method (either with Id or BackgroundTaskQuery), and optionally, you can configure some execution metadata modification (for example, to pass some data from kafka callback or request directly to background task)

await _runner
    .ProceedBackgroundTask
    .WithId(backgroundTaskId)
    .WithoutExecutionMetadataModification()
    .ProceedAsync(default);

ProceedAsync method will return ProceedTaskResult object, which can be one of success, task not found, multiple tasks found, invalid task (background task is configured to use different IBackgroundTask<,,,> handler), execution metadata modification failure (execution metadata of task is configured to use different type of IBackgroundTaskExecutionMetadata)