Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix race condition in GetName #1571

Merged
merged 1 commit into from
May 3, 2023
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
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