Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Avoid locking on every ValidationAttributeStore lookup.
  • Loading branch information
eiriktsarpalis committed Feb 23, 2023
commit b7cabf362477d43639c945a9e55957ff889b3b8d
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
Expand All @@ -19,7 +20,7 @@ namespace System.ComponentModel.DataAnnotations
/// </remarks>
internal sealed class ValidationAttributeStore
{
private readonly Dictionary<Type, TypeStoreItem> _typeStoreItems = new Dictionary<Type, TypeStoreItem>();
private readonly ConcurrentDictionary<Type, TypeStoreItem> _typeStoreItems = new();

/// <summary>
/// Gets the singleton <see cref="ValidationAttributeStore" />
Expand Down Expand Up @@ -118,16 +119,14 @@ private TypeStoreItem GetTypeStoreItem([DynamicallyAccessedMembers(TypeStoreItem
{
Debug.Assert(type != null);

lock (_typeStoreItems)
{
if (!_typeStoreItems.TryGetValue(type, out TypeStoreItem? item))
{
AttributeCollection attributes = TypeDescriptor.GetAttributes(type);
item = new TypeStoreItem(type, attributes);
_typeStoreItems[type] = item;
}
return _typeStoreItems.GetOrAdd(type, AddTypeStoreItem);

return item;
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2067:UnrecognizedReflectionPattern",
Justification = "The parameter in the parent method has already been marked DynamicallyAccessedMemberTypes.All.")]
static TypeStoreItem AddTypeStoreItem(Type type)
{
AttributeCollection attributes = TypeDescriptor.GetAttributes(type);
return new TypeStoreItem(type, attributes);
}
}

Expand Down