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

Hug*_*opp 5 azure azure-service-fabric

我想实现一个Azure的最简单的使用服务织物可靠地收集,一个Hello World例子,因为它是,的I?Reliable?Dictionary

此链接中给出了一个示例,但是此示例需要一个StateManager对象,我不确定如何创建甚至它是什么。似乎需要演员,而且我现在想避免演员。

谁能提供一个例子吗?

提前谢谢了

Hug*_*opp 8

没关系,我找到了答案。

关键的一点是,一个不能建立在无状态服务可靠的集合,我们一定要建立一个有状态的服务,如果我们要使用的可靠集合

在这里,我找到了一个可靠字典的实现示例。接下来粘贴代码,该代码应放在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);
}
Run Code Online (Sandbox Code Playgroud)