我读到this关于使用可靠集合的文章,其中提到一旦将对象提供给可靠集合,就不得修改该对象,并且更新可靠集合中的值的正确方法是获取复制(克隆)该值,检查克隆值,然后更新 RC 中的克隆值。
使用不当:
using (ITransaction tx = StateManager.CreateTransaction()) {
// Use the user’s name to look up their data
ConditionalValue<User> user =
await m_dic.TryGetValueAsync(tx, name);
// The user exists in the dictionary, update one of their properties.
if (user.HasValue) {
// The line below updates the property’s value in memory only; the
// new value is NOT serialized, logged, & sent to secondary replicas.
user.Value.LastLogin = DateTime.UtcNow; // Corruption!
await tx.CommitAsync();
}
}
我的问题是:为什么我把对象交给 RC 后就不能修改它了?为什么我必须在更改对象之前克隆该对象?为什么我不能做类似的事情(在同一事务中更新对象):
using (ITransaction tx = StateManager.CreateTransaction()) {
// Use the user’s name to look up their data
ConditionalValue<User> user =
await m_dic.TryGetValueAsync(tx, name);
// The user exists in the dictionary, update one of their properties.
if (user.HasValue) {
// The line below updates the property’s value in memory only; the
// new value is NOT serialized, logged, & sent to secondary replicas.
user.Value.LastLogin = DateTime.UtcNow;
// Update
await m_dic.SetValue(tx, name, user.Value);
await tx.CommitAsync();
}
}
谢谢!
最佳答案
可靠字典是一个复制的对象存储。如果您更新可靠字典中的对象而不通过可靠字典(例如 TryUpdateAsync ),那么您可能会破坏状态。
例如,如果您使用引用更改 Reliable Dictionary 内的对象,则更改将不会复制到辅助副本。 这是因为 Reliable Dictionary 不知道您更改了 TValue 之一。因此,如果副本发生故障转移,更改将会丢失。
以上是最简单的例子。直接修改对象可能会导致其他严重问题,例如以多种方式破坏 ACID。
关于c# - 修改 Service Fabric 可靠集合中的原始对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41348756/