Skip to content

Commit

Permalink
Make Interceptor more thread-safe
Browse files Browse the repository at this point in the history
Several methods in `Interceptor` currently read and modify a private
dictionary without any synchronization or locking, which means that if
someone tries to perform several setups concurrently on the same mock,
they might run into a some multithreading-related exception every now
and then.
  • Loading branch information
stakx committed Jun 27, 2017
1 parent 08d88d1 commit 970981d
Showing 1 changed file with 23 additions and 14 deletions.
37 changes: 23 additions & 14 deletions Source/Interceptor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,13 @@ internal void VerifyAll()

private void VerifyOrThrow(Func<IProxyCall, bool> match)
{
var failures = calls.Values.Where(match).ToArray();
if (failures.Length > 0)
lock (calls)
{
throw new MockVerificationException(failures);
var failures = calls.Values.Where(match);
if (failures.Any())
{
throw new MockVerificationException(failures.ToArray());
}
}
}

Expand All @@ -96,26 +99,32 @@ public void AddCall(IProxyCall call, SetupKind kind)

if (!call.IsConditional)
{
// if it's not a conditional call, we do
// all the override setups.
// TODO maybe add the conditionals to other
// record like calls to be user friendly and display
// somethig like: non of this calls were performed.
if (calls.ContainsKey(key))
lock (calls)
{
// Remove previous from ordered calls
InterceptionContext.RemoveOrderedCall(calls[key]);
}
// if it's not a conditional call, we do
// all the override setups.
// TODO maybe add the conditionals to other
// record like calls to be user friendly and display
// somethig like: non of this calls were performed.
if (calls.ContainsKey(key))
{
// Remove previous from ordered calls
InterceptionContext.RemoveOrderedCall(calls[key]);
}

calls[key] = call;
calls[key] = call;
}
}

InterceptionContext.AddOrderedCall(call);
}

internal void ClearCalls()
{
calls.Clear();
lock (calls)
{
calls.Clear();
}
}

private IEnumerable<IInterceptStrategy> InterceptionStrategies()
Expand Down

0 comments on commit 970981d

Please sign in to comment.