Skip to content

Commit

Permalink
Switch to ConcurrentDictionary for better thread-safety
Browse files Browse the repository at this point in the history
  • Loading branch information
stakx committed Feb 14, 2022
1 parent e78509b commit 5014bd0
Showing 1 changed file with 4 additions and 7 deletions.
11 changes: 4 additions & 7 deletions src/Moq/StubbedPropertiesSetup.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors.
// All rights reserved. Licensed under the BSD 3-Clause License; see License.txt.

using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq.Expressions;
Expand All @@ -11,13 +12,13 @@ namespace Moq
{
internal sealed class StubbedPropertiesSetup : Setup
{
private readonly Dictionary<string, object> values;
private readonly ConcurrentDictionary<string, object> values;
private readonly DefaultValueProvider defaultValueProvider;

public StubbedPropertiesSetup(Mock mock, DefaultValueProvider defaultValueProvider = null)
: base(originalExpression: null, mock, new PropertyAccessorExpectation(mock))
{
this.values = new Dictionary<string, object>();
this.values = new ConcurrentDictionary<string, object>();
this.defaultValueProvider = defaultValueProvider ?? mock.DefaultValueProvider;

this.MarkAsVerifiable();
Expand Down Expand Up @@ -60,11 +61,7 @@ protected override void ExecuteCore(Invocation invocation)
Debug.Assert(invocation.Method.IsGetAccessor());

var propertyName = invocation.Method.Name.Substring(4);
if (!this.values.TryGetValue(propertyName, out var value))
{
value = this.values[propertyName] = this.Mock.GetDefaultValue(invocation.Method, out _, this.defaultValueProvider);
}

var value = this.values.GetOrAdd(propertyName, pn => this.Mock.GetDefaultValue(invocation.Method, out _, this.defaultValueProvider));
invocation.ReturnValue = value;
}
}
Expand Down

0 comments on commit 5014bd0

Please sign in to comment.