@@ -25,17 +25,33 @@ public static class LinqExtensions
25
25
/// <returns></returns>
26
26
public static bool IsEmpty < T > ( this IEnumerable < T > enumerable ) => enumerable is null || ! enumerable . Any ( ) ;
27
27
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
29
29
{
30
30
if ( dictionary is null || key is null )
31
31
return defaultValue ;
32
32
33
- if ( ! dictionary . ContainsKey ( key ) )
33
+ if ( dictionary is ConcurrentDictionary < TKey , TValue > cDict )
34
34
{
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 ) ;
37
39
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
+ }
39
55
}
40
56
41
57
if ( dictionary [ key ] is TOut o )
@@ -49,22 +65,32 @@ public static class LinqExtensions
49
65
if ( dictionary is null || key is null )
50
66
return defaultValueFunc ( ) ;
51
67
52
- if ( ! dictionary . ContainsKey ( key ) )
68
+ if ( dictionary is ConcurrentDictionary < TKey , Task < TValue ? > > cDict )
53
69
{
54
- var defaultValue = defaultValueFunc ( ) ;
55
- if ( defaultValue is Task < TValue ? > value )
70
+ if ( ! cDict . ContainsKey ( key ) )
56
71
{
57
- if ( dictionary is ConcurrentDictionary < TKey , Task < TValue ? > > cDict )
58
- {
72
+ var defaultValue = defaultValueFunc ( ) ;
73
+ if ( defaultValue is Task < TValue ? > value )
59
74
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 ) )
62
84
{
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 ;
64
90
}
65
91
}
66
- return defaultValue ;
67
92
}
93
+
68
94
return dictionary [ key ] ;
69
95
}
70
96
0 commit comments