最简单的服务结构可靠集合(字典)示例

时间:2017-06-21 16:24:33

标签: azure azure-service-fabric

我尝试实现最简单的Azure Service Fabric Reliable CollectionHello World示例的使用,原来是{{ 1}}。

this link中给出了一个示例,但此示例需要一个I​Reliable​Dictionary对象,我不确定如何创建或甚至是什么。似乎需要Actor,我现在正在寻求避免使用Actors。

有人能举例说明吗?

非常感谢提前

1 个答案:

答案 0 :(得分:7)

没关系,我找到了答案。

关键是,无法在无状态服务中创建可靠的集合,如果我们想要使用,我们必须创建有状态服务 Reliable Collections

Here我找到了一个可靠字典实现的例子。我将代码粘贴到MyStatefulService.cs类:

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);
}