c# - 修改 Service Fabric 可靠集合中的原始对象

标签 c# .net azure azure-service-fabric

我读到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/

相关文章:

azure - 断电后使用 Azure 恢复上传

c# - 在派生类中将属性设置为只读

c# - Azure EventHub - EventHubClient.Send() 导致 NullReferenceException

c# - C#中快速匹配DataTable和String Array的方法

c# - 为什么 long 和 decimal 之间的 Equals 不可交换?

.net - EF 等效于 SqlCommand.ExecuteNonQuery 影响的行

.net - 调度程序/通知服务建议/架构决策

azure - 从 Azure 恢复服务恢复 Azure VM

c# - 为什么principalsearcher 代码显着变慢

c# - CSV 字符串处理