Search code examples
azureazure-service-fabric

Simplest Service Fabric Reliable Collection (Dictionary) example


I'm trying to implement the simplest usage of an Azure's Service Fabric Reliable Collection --- a Hello World example, as it were --- of an I​Reliable​Dictionary.

In this link an example is given. Yet this example requires a StateManager object, which I'm unsure how to create or even what it is. It seems an Actor is needed, and I'm looking to avoid Actors for now.

Could anyone provide an example of this?

Many thanks in advance


Solution

  • Never mind, I found the answer.

    The crucial point is that one can't create reliable collections in Stateless Services, we necessarily need to create a Stateful Service if we want to make use of the Reliable Collections.

    Here I found an example of an implementation of a Reliable Dictionary. I paste the code next, which should go in the MyStatefulService.cs class:

    protected override async Task RunAsync(CancellationToken cancellationToken)
    {
    
    var myDictionary = await this.StateManager.GetOrAddAsync<IReliableDictionary<string, long>>("myDictionary");
    
    while (true)
    {
        cancellationToken.ThrowIfCancellationRequested();
    
        using (var tx = this.StateManager.CreateTransaction())
        {
            var result = await myDictionary.TryGetValueAsync(tx, "Counter");
    
            ServiceEventSource.Current.ServiceMessage(this, "Current Counter Value: {0}",
                result.HasValue ? result.Value.ToString() : "Value does not exist.");
    
            await myDictionary.AddOrUpdateAsync(tx, "Counter", 0, (key, value) => ++value);
    
            // If an exception is thrown before calling CommitAsync, the transaction aborts, all changes are
            // discarded, and nothing is saved to the secondary replicas.
            await tx.CommitAsync();
        }
    
        await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
    }