Working with SharedActivation

Once you've configured a SharedActivation instance, you'll use it to safely execute operations on the underlying activation across multiple processes. All operations must go through the ExecuteWithLock methods to ensure proper synchronization.

Core Concepts

  • Exclusive Access: Only one process can modify the activation at a time

  • State Synchronization: The activation state is automatically reloaded from persistence when a lock is acquired

  • Safe Release: Locks are always released, even if operations throw exceptions

Initializing the Activation

Before using a SharedActivation, you must initialize it:

// Initialize the activation
await activation.InitializeWithLock(cancellationToken);

Executing Operations

All interactions with a SharedActivation must use one of the ExecuteWithLock methods:

Execute an Action (No Return Value)

await activation.ExecuteWithLock(async activation => 
{
    // Perform operations using the activation 'activation'
    await activation.Activate(credentials);
}, cancellationToken);

Execute a Function (And Return Value)

// Async function
var featureAcquired = await activation.ExecuteWithLock(async activation =>
{
    // Return some value asynchronously
    if (activation.Features.TryGet("feature-key", out var feature) &&
        feature.Available >= 1)
    {
        await activation.CheckoutFeature(feature, 1);
        return true;
    }

    return false;
}, cancellationToken); 

// Sync function
var features = await activation.ExecuteWithLock(activation =>
{
    return activation.Features;
}, cancellationToken);

State Synchronization Each time a ExecuteWithLock method is called:

  • The system-wide lock is acquired

  • The activation state is automatically reloaded from persistent storage

  • Your action/function executes with the up-to-date activation state

  • Any changes are persisted to storage

  • The lock is released

This ensures that your code always sees changes made by other processes.

Thread Safety Considerations

While SharedActivation handles cross-process synchronization, be aware that:

  • Operations within a single ExecuteWithLock block are atomic from other processes' perspective

  • The lock is held for the entire duration of your action/function

  • Keep operations within the lock as brief as possible to avoid blocking other processes

  • Don't perform long-running operations within the lock

Last updated

Was this helpful?