我尝试实现最简单的Azure Service Fabric Reliable Collection,Hello World
示例的使用,原来是{{ 1}}。
在this link中给出了一个示例,但此示例需要一个IReliableDictionary
对象,我不确定如何创建或甚至是什么。似乎需要Actor,我现在正在寻求避免使用Actors。
有人能举例说明吗?
非常感谢提前
答案 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);
}