Pergunta

Is there any clean way to get WCF calls to apply max degree of parallellism of 1 based on a request argument?

assume the following code:

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

I want to handle a maximum of 1 parallell calls based on entityId here. I know I can set concurrency options for the WCF, but this is either concurrent or single threaded. but it seems a bit too drastic to set it to single call for the entire operation when all I need os single call per entityId.

I assume I have to handroll this, but what would be my best bet here w/o involving an actor model lib?

Foi útil?

Solução

First, consider if you really need to synchronize based on an ID. Are you foreseeing a scale-up issue otherwise? As always, testing and benchmarking is your best option before seeking this possibly premature optimization.

That said, if the amount of entity IDs is not large, you could use this simple solution:

[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
     }
  }
}

This does not deal with cleanup, so if you have a lot of entities, the dictionary would grow to contain a lock object for each one.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top