Skip to content

Commit

Permalink
Refactor other use of ConcurrentDictionary GetOrAdd
Browse files Browse the repository at this point in the history
  • Loading branch information
lukebakken committed May 20, 2020
1 parent 75ac0db commit ac4ad8b
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 11 deletions.
16 changes: 7 additions & 9 deletions projects/RabbitMQ.Client/client/impl/AsyncConsumerWorkService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,8 @@ namespace RabbitMQ.Client.Impl
{
internal sealed class AsyncConsumerWorkService : ConsumerWorkService
{
private readonly ConcurrentDictionary<IModel, WorkPool> _workPools;
private readonly Func<IModel, WorkPool> _startNewWorkPoolFunc;

public AsyncConsumerWorkService()
{
_workPools = new ConcurrentDictionary<IModel, WorkPool>();
_startNewWorkPoolFunc = model => StartNewWorkPool(model);
}
private readonly ConcurrentDictionary<IModel, WorkPool> _workPools = new ConcurrentDictionary<IModel, WorkPool>();
private readonly Func<IModel, WorkPool> _startNewWorkPoolFunc = model => StartNewWorkPool(model);

public void Schedule<TWork>(ModelBase model, TWork work) where TWork : Work
{
Expand All @@ -25,10 +19,14 @@ public void Schedule<TWork>(ModelBase model, TWork work) where TWork : Work
*
* The lock is necessary because calling the value delegate is not atomic.
*/
WorkPool workPool;

lock (_workPools)
{
_workPools.GetOrAdd(model, _startNewWorkPoolFunc).Enqueue(work);
workPool = _workPools.GetOrAdd(model, _startNewWorkPoolFunc);
}

workPool.Enqueue(work);
}

private static WorkPool StartNewWorkPool(IModel model)
Expand Down
12 changes: 10 additions & 2 deletions projects/RabbitMQ.Client/client/impl/ConsumerWorkService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,21 @@ namespace RabbitMQ.Client.Impl
class ConsumerWorkService
{
private readonly ConcurrentDictionary<IModel, WorkPool> _workPools = new ConcurrentDictionary<IModel, WorkPool>();
private readonly Func<IModel, WorkPool> _startNewWorkPoolFunc = model => StartNewWorkPool(model);

public void AddWork(IModel model, Action fn)
{
_workPools.GetOrAdd(model, StartNewWorkPool).Enqueue(fn);
WorkPool workPool;

lock (_workPools)
{
workPool = _workPools.GetOrAdd(model, _startNewWorkPoolFunc);
}

workPool.Enqueue(fn);
}

private WorkPool StartNewWorkPool(IModel model)
private static WorkPool StartNewWorkPool(IModel model)
{
var newWorkPool = new WorkPool();
newWorkPool.Start();
Expand Down

0 comments on commit ac4ad8b

Please sign in to comment.