【发布时间】:2018-01-12 07:09:06
【问题描述】:
我有一个类似的类(下面的简化版)
public static class ThingyLookup
{
private static ConcurrentDictionary<int, Thingy> cache;
public static UpsertThingies (IEnumerable<Thingy> thingies)
{
foreach (var thingy in thingies)
{
if (thingy.Status == ThingyStatus.Deleted)
{
Thingy removed;
cache.TryRemove(thingy.Id, out removed);
}
else
{
cache.TryUpdate(thingy.Id, thingy);
}
}
}
public static IEnumerable<Thingy> Find (string query)
{
return (from thingy in cache.Values
where thingy != null && thingy.Name.Contains(query)
orderby thingy.Name
select thingy);
}
}
如果 2 个线程正在运行 Find 查询,是否有可能发生类似
- 线程 1 评估
thingy != null && thingy.Name.Contains(query)为真的情况 - 线程 2 将字典中相同的
thingy更新为null - 线程 1 尝试在
orderby中使用thingy.Name,从而导致 NRE
??如果是这样,如何在不造成死锁的情况下进行预防?
【问题讨论】:
-
我假设
Find中的thingies应该是cache?如果您的示例是可编译的,那就太好了。 -
thingy中的UpsertThingies怎么可能是null而不会导致cache.TryUpdate抛出 NRE?话虽如此,不可能将nul添加到您的字典中。 -
@Damien_The_Unbeliever 我现在修好了。对不起。
标签: c# .net multithreading concurrency