@@ -22,17 +22,33 @@ public static class LinqExtensions
22
22
/// <returns></returns>
23
23
public static bool IsEmpty < T > ( this IEnumerable < T > enumerable ) => enumerable is null || ! enumerable . Any ( ) ;
24
24
25
- public static TOut ? Get < TOut , TKey , TValue > ( this IDictionary < TKey , TValue > dictionary , TKey key , TOut ? defaultValue = default )
25
+ public static TOut ? Get < TOut , TKey , TValue > ( this IDictionary < TKey , TValue > dictionary , TKey key , TOut ? defaultValue = default ) where TKey : notnull
26
26
{
27
27
if ( dictionary is null || key is null )
28
28
return defaultValue ;
29
29
30
- if ( ! dictionary . ContainsKey ( key ) )
30
+ if ( dictionary is ConcurrentDictionary < TKey , TValue > cDict )
31
31
{
32
- if ( defaultValue is TValue value )
33
- dictionary . Add ( key , value ) ;
32
+ if ( ! cDict . ContainsKey ( key ) )
33
+ {
34
+ if ( defaultValue is TValue value )
35
+ cDict . TryAdd ( key , value ) ;
34
36
35
- return defaultValue ;
37
+ return defaultValue ;
38
+ }
39
+ }
40
+ else
41
+ {
42
+ lock ( dictionary )
43
+ {
44
+ if ( ! dictionary . ContainsKey ( key ) )
45
+ {
46
+ if ( defaultValue is TValue value )
47
+ dictionary . Add ( key , value ) ;
48
+
49
+ return defaultValue ;
50
+ }
51
+ }
36
52
}
37
53
38
54
if ( dictionary [ key ] is TOut o )
@@ -46,22 +62,32 @@ public static class LinqExtensions
46
62
if ( dictionary is null || key is null )
47
63
return defaultValueFunc ( ) ;
48
64
49
- if ( ! dictionary . ContainsKey ( key ) )
65
+ if ( dictionary is ConcurrentDictionary < TKey , Task < TValue ? > > cDict )
50
66
{
51
- var defaultValue = defaultValueFunc ( ) ;
52
- if ( defaultValue is Task < TValue ? > value )
67
+ if ( ! cDict . ContainsKey ( key ) )
53
68
{
54
- if ( dictionary is ConcurrentDictionary < TKey , Task < TValue ? > > cDict )
55
- {
69
+ var defaultValue = defaultValueFunc ( ) ;
70
+ if ( defaultValue is Task < TValue ? > value )
56
71
cDict . TryAdd ( key , value ) ;
57
- }
58
- else
72
+
73
+ return defaultValue ;
74
+ }
75
+ }
76
+ else
77
+ {
78
+ lock ( dictionary )
79
+ {
80
+ if ( ! dictionary . ContainsKey ( key ) )
59
81
{
60
- dictionary . Add ( key , value ) ;
82
+ var defaultValue = defaultValueFunc ( ) ;
83
+ if ( defaultValue is Task < TValue ? > value )
84
+ dictionary . Add ( key , value ) ;
85
+
86
+ return defaultValue ;
61
87
}
62
88
}
63
- return defaultValue ;
64
89
}
90
+
65
91
return dictionary [ key ] ;
66
92
}
67
93
0 commit comments