1

有没有什么干净的方法可以让 WCF 调用根据请求参数应用最大并行度 1?

假设以下代码:

 public void MyWcfOperation(int entityId, other arguments)
 {
      //do stuff with entity with id = entityId
 }

我想在这里根据 entityId 处理最多 1 个并行调用。我知道我可以为 WCF 设置并发选项,但这是并发的或单线程的。但是当我只需要每个 entityId 的单个调用时,将其设置为整个操作的单个调用似乎有点过于激烈。

我想我必须手动处理这个,但是如果不涉及演员模型库,我最好的选择是什么?

4

1 回答 1

1

首先,考虑是否真的需要基于 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
     }
  }
}

这不涉及清理,因此如果您有很多实体,字典将增长为包含每个实体的锁定对象。

于 2014-02-19T09:15:13.423 回答