【发布时间】:2022-10-17 21:37:42
【问题描述】:
我有一个程序可以像这样更新 Azure 表存储表中的条目:
- 从按 partitionKey 和 item Id 过滤的表中恢复条目
- 对已恢复对象的某些属性进行了一些更改。
- 将更改保存回 BD。
因为我读过 Azure 存储表使用乐观并发和 Etag 属性(例如根据this,或者这个stackoverflow 问题on what is stored in Etag) 为了管理它,我想出了以下代码:
var query = table.CreateQuery<DynamicTableEntity>()
.Where(d => d.PartitionKey == customItem.PartitionKey
&& d.Properties[nameof(CustomItem.CustomItemId)].GuidValue == Guid.Parse(StringValueOfId)
)
.AsTableQuery();
var tr = table.ExecuteQuery<DynamicTableEntity>(query);
if (tr != null)
{
var entity = new DynamicTableEntity(customItem.PartitionKey, StringValueOfId);
entity.Properties.Add("MyDate", dateValue);
entity.Properties.Add("CustomProperty", new EntityProperty(JsonConvert.SerializeObject(customItem)));
entity.ETag = tr.FirstOrDefault().ETag;
TableOperation mergeOperation = TableOperation.Replace(entity);
try
{
TableResult result = await table.ExecuteAsync(mergeOperation);
}
catch (Exception ex)
{
throw new StorageException("Error saving data:" + ex.Message);
}
}
现在我仍然遇到并发问题。基本上我的“CustomProperty”有 一个序列化的属性,其中一些字段为空。看起来,A和B都尝试 同时设置“CustomProperty”的值。其中之一是覆盖 对方的变化。
然而,由于“entity.ETag”的设置,我预计这是不可能的。 我期待如果A和B同时读取BD,然后A更新, 由于 entity.ETag 的值不匹配,B 的更新将失败。
有人可以告诉我我做错了什么吗?我不明白如何正确避免这些 并发问题?
【问题讨论】:
标签: azure azure-table-storage azure-tablequery