Skip to content

Fix: Fixed System.ArgumentException caused by adding the same key #12302

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

Merged
merged 2 commits into from
May 11, 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
54 changes: 40 additions & 14 deletions src/Files.Shared/Extensions/LinqExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,33 @@ public static class LinqExtensions
/// <returns></returns>
public static bool IsEmpty<T>(this IEnumerable<T> enumerable) => enumerable is null || !enumerable.Any();

public static TOut? Get<TOut, TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TOut? defaultValue = default)
public static TOut? Get<TOut, TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TOut? defaultValue = default) where TKey : notnull
{
if (dictionary is null || key is null)
return defaultValue;

if (!dictionary.ContainsKey(key))
if (dictionary is ConcurrentDictionary<TKey, TValue> cDict)
{
if (defaultValue is TValue value)
dictionary.Add(key, value);
if (!cDict.ContainsKey(key))
{
if (defaultValue is TValue value)
cDict.TryAdd(key, value);

return defaultValue;
return defaultValue;
}
}
else
{
lock (dictionary)
{
if (!dictionary.ContainsKey(key))
{
if (defaultValue is TValue value)
dictionary.Add(key, value);

return defaultValue;
}
}
}

if (dictionary[key] is TOut o)
Expand All @@ -49,22 +65,32 @@ public static class LinqExtensions
if (dictionary is null || key is null)
return defaultValueFunc();

if (!dictionary.ContainsKey(key))
if (dictionary is ConcurrentDictionary<TKey, Task<TValue?>> cDict)
{
var defaultValue = defaultValueFunc();
if (defaultValue is Task<TValue?> value)
if (!cDict.ContainsKey(key))
{
if (dictionary is ConcurrentDictionary<TKey, Task<TValue?>> cDict)
{
var defaultValue = defaultValueFunc();
if (defaultValue is Task<TValue?> value)
cDict.TryAdd(key, value);
}
else

return defaultValue;
}
}
else
{
lock (dictionary)
{
if (!dictionary.ContainsKey(key))
{
dictionary.Add(key, value);
var defaultValue = defaultValueFunc();
if (defaultValue is Task<TValue?> value)
dictionary.Add(key, value);

return defaultValue;
}
}
return defaultValue;
}

return dictionary[key];
}

Expand Down