我正在尝试为可靠的字典实现基于游标的分页。我知道IReliableDictionary
键必须实现IComparable
,而IReliableDictionary
这个方法用于枚举字典条目:
IAsyncEnumerable<KeyValuePair<TKey,TValue>>>
CreateEnumerableAsync (
ITransaction txn,
Func<TKey,bool> filter,
EnumerationMode enumerationMode);
当使用EnumerationMode.Ordered
时,我假设我们根据密钥的IComparable
实现枚举键值对。
我们是否还可以假设filter
参数按照密钥的IComparable
实现的顺序应用于每个密钥?也许另一种要问的方式 - 键是按照IComparable
实现的顺序在内存中布置和/或枚举的?如果是,是否记录了此行为,还是应将其视为可能更改的实现细节?
我使用Voting Web样本进行了一项实验,并且键确实按照IComparable
实现的顺序进行过滤,但有一些注意事项:
VotingData.Controllers.VoteDataController
有以下get和put操作列出并添加投票类别:
[HttpPut("{name}")]
public async Task<IActionResult> Put(string name)
{
IReliableDictionary<string, int> votesDictionary = await this.stateManager.GetOrAddAsync<IReliableDictionary<string, int>>("counts");
using (ITransaction tx = this.stateManager.CreateTransaction())
{
await votesDictionary.AddOrUpdateAsync(tx, name, 1, (key, oldvalue) => oldvalue + 1);
await tx.CommitAsync();
}
return new OkResult();
}
我修改了Get
以按顺序枚举votesDictionary
,并应用了一个过滤器来构建过滤器看到的键列表:
[HttpGet]
public async Task<IActionResult> Get()
{
CancellationToken ct = new CancellationToken();
IReliableDictionary<string, int> votesDictionary = await this.stateManager.GetOrAddAsync<IReliableDictionary<string, int>>("counts");
var filteredKeys = new List<string>();
using (ITransaction tx = this.stateManager.CreateTransaction())
{
IAsyncEnumerable<KeyValuePair<string, int>> list = await votesDictionary.CreateEnumerableAsync(tx, key =>
{
lock (this.locker)
{
filteredKeys.Add(key);
return true;
}
},
EnumerationMode.Ordered);
IAsyncEnumerator<KeyValuePair<string, int>> enumerator = list.GetAsyncEnumerator();
List<KeyValuePair<string, int>> result = new List<KeyValuePair<string, int>>();
while (await enumerator.MoveNextAsync(ct))
{
result.Add(enumerator.Current);
}
return this.Json(result);
}
}
我以随机字母顺序向字典添加了键,并刷新了页面以运行Get
查询。在每次刷新时,filteredKeys
集合按字母顺序排列我的条目。如上所述,集合有时包含某些字符串的重复条目。当我从集合中删除项目并刷新页面时,我发现删除的键仍然添加到filteredKeys
,尽管这些元素未在结果枚举中返回。