ConcurrentDictionary.TryUpdate方法需要将comparisonValue与具有指定键的元素的值进行比较.但如果我尝试做这样的事情:
if (!_store.TryGetValue(book.Id, out Book existing))
{
throw new KeyNotFoundException();
}
if (!_store.TryUpdate(book.Id, book, existing))
{
throw new Exception("Unable to update the book");
}
Run Code Online (Sandbox Code Playgroud)
当多个线程同时更新一本书时,它会抛出一个异常,因为existingbook在另一个线程中被更改了.
我不能使用索引器,因为它添加了书,如果它不存在,我不能检查键是否存在,因为它也不会原子.
我改变了我的代码:
while (true)
{
if (!_store.TryGetValue(book.Id, out Book existing))
{
throw new KeyNotFoundException();
}
if (_store.TryUpdate(book.Id, book, existing))
{
break;
}
}
Run Code Online (Sandbox Code Playgroud)
但我担心无限循环.
但是如果我在Update和Delete方法上使用锁定,我将失去使用ConcurrentDictionary的优势.
解决问题的正确方法是什么?