首先,考虑是否真的需要基于 ID 进行同步。您是否预见到了扩大规模的问题?与往常一样,在寻求这种可能过早的优化之前,测试和基准测试是您的最佳选择。
也就是说,如果实体 ID 的数量不大,您可以使用这个简单的解决方案:
[ServiceBehavior(
InstanceContextMode = InstanceContextMode.Single, // required to hold the dictionary through calls
ConcurrencyMode = ConcurrencyMode.Multiple] // let WCF run all the calls concurrently
class Service
{
private readonly ConcurrentDictionary<int, object> _locks = new ConcurrentDictionary<int, object>();
public void MyWcfOperation(int entityId, other arguments)
{
lock (_locks.GetOrAdd(entityId, i => new Object())
{
// do stuff with entity with id = entityId
}
}
}
这不涉及清理,因此如果您有很多实体,字典将增长为包含每个实体的锁定对象。