Skip to content

Commit

Permalink
Fix race condition in GetName (#1571)
Browse files Browse the repository at this point in the history
  • Loading branch information
foriequal0 committed May 3, 2023
1 parent f1d244b commit 3d1356a
Showing 1 changed file with 25 additions and 5 deletions.
30 changes: 25 additions & 5 deletions src/NJsonSchema/Infrastructure/TypeExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,29 +12,49 @@
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Threading;

namespace NJsonSchema.Infrastructure
{
/// <summary>Provides extension methods for reading contextual type names and descriptions.</summary>
public static class TypeExtensions
{
private static ReaderWriterLockSlim _namesLock = new ReaderWriterLockSlim();
private static Dictionary<ContextualMemberInfo, string> _names = new Dictionary<ContextualMemberInfo, string>();

/// <summary>Gets the name of the property for JSON serialization.</summary>
/// <returns>The name.</returns>
internal static string GetName(this ContextualAccessorInfo accessorInfo)
{
if (!_names.ContainsKey(accessorInfo))
_namesLock.EnterUpgradeableReadLock();
try
{
lock (_names)
if (_names.TryGetValue(accessorInfo, out var name))
{
if (!_names.ContainsKey(accessorInfo))
return name;
}

_namesLock.EnterWriteLock();
try
{
if (_names.TryGetValue(accessorInfo, out name))
{
_names[accessorInfo] = GetNameWithoutCache(accessorInfo);
return name;
}

name = GetNameWithoutCache(accessorInfo);
_names[accessorInfo] = name;
return name;
}
finally
{
_namesLock.ExitWriteLock();
}
}
finally
{
_namesLock.ExitUpgradeableReadLock();
}
return _names[accessorInfo];
}

private static string GetNameWithoutCache(ContextualAccessorInfo accessorInfo)
Expand Down

0 comments on commit 3d1356a

Please sign in to comment.