Skip to content

Commit 386b0dd

Browse files
authored
Fix: Fixed System.ArgumentException caused by adding the same key (#12302)
1 parent bea5c27 commit 386b0dd

File tree

1 file changed

+40
-14
lines changed

1 file changed

+40
-14
lines changed

src/Files.Shared/Extensions/LinqExtensions.cs

Lines changed: 40 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -25,17 +25,33 @@ public static class LinqExtensions
2525
/// <returns></returns>
2626
public static bool IsEmpty<T>(this IEnumerable<T> enumerable) => enumerable is null || !enumerable.Any();
2727

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

33-
if (!dictionary.ContainsKey(key))
33+
if (dictionary is ConcurrentDictionary<TKey, TValue> cDict)
3434
{
35-
if (defaultValue is TValue value)
36-
dictionary.Add(key, value);
35+
if (!cDict.ContainsKey(key))
36+
{
37+
if (defaultValue is TValue value)
38+
cDict.TryAdd(key, value);
3739

38-
return defaultValue;
40+
return defaultValue;
41+
}
42+
}
43+
else
44+
{
45+
lock (dictionary)
46+
{
47+
if (!dictionary.ContainsKey(key))
48+
{
49+
if (defaultValue is TValue value)
50+
dictionary.Add(key, value);
51+
52+
return defaultValue;
53+
}
54+
}
3955
}
4056

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

52-
if (!dictionary.ContainsKey(key))
68+
if (dictionary is ConcurrentDictionary<TKey, Task<TValue?>> cDict)
5369
{
54-
var defaultValue = defaultValueFunc();
55-
if (defaultValue is Task<TValue?> value)
70+
if (!cDict.ContainsKey(key))
5671
{
57-
if (dictionary is ConcurrentDictionary<TKey, Task<TValue?>> cDict)
58-
{
72+
var defaultValue = defaultValueFunc();
73+
if (defaultValue is Task<TValue?> value)
5974
cDict.TryAdd(key, value);
60-
}
61-
else
75+
76+
return defaultValue;
77+
}
78+
}
79+
else
80+
{
81+
lock (dictionary)
82+
{
83+
if (!dictionary.ContainsKey(key))
6284
{
63-
dictionary.Add(key, value);
85+
var defaultValue = defaultValueFunc();
86+
if (defaultValue is Task<TValue?> value)
87+
dictionary.Add(key, value);
88+
89+
return defaultValue;
6490
}
6591
}
66-
return defaultValue;
6792
}
93+
6894
return dictionary[key];
6995
}
7096

0 commit comments

Comments
 (0)