diff --git a/src/Files.Shared/Extensions/LinqExtensions.cs b/src/Files.Shared/Extensions/LinqExtensions.cs
index 71f85dd76396..03ede19a8aef 100644
--- a/src/Files.Shared/Extensions/LinqExtensions.cs
+++ b/src/Files.Shared/Extensions/LinqExtensions.cs
@@ -25,17 +25,33 @@ public static class LinqExtensions
///
public static bool IsEmpty(this IEnumerable enumerable) => enumerable is null || !enumerable.Any();
- public static TOut? Get(this IDictionary dictionary, TKey key, TOut? defaultValue = default)
+ public static TOut? Get(this IDictionary 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 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)
@@ -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> cDict)
{
- var defaultValue = defaultValueFunc();
- if (defaultValue is Task value)
+ if (!cDict.ContainsKey(key))
{
- if (dictionary is ConcurrentDictionary> cDict)
- {
+ var defaultValue = defaultValueFunc();
+ if (defaultValue is Task 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 value)
+ dictionary.Add(key, value);
+
+ return defaultValue;
}
}
- return defaultValue;
}
+
return dictionary[key];
}