@@ -22,17 +22,33 @@ public static class LinqExtensions
2222 /// <returns></returns>
2323 public static bool IsEmpty < T > ( this IEnumerable < T > enumerable ) => enumerable is null || ! enumerable . Any ( ) ;
2424
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
2626 {
2727 if ( dictionary is null || key is null )
2828 return defaultValue ;
2929
30- if ( ! dictionary . ContainsKey ( key ) )
30+ if ( dictionary is ConcurrentDictionary < TKey , TValue > cDict )
3131 {
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 ) ;
3436
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+ }
3652 }
3753
3854 if ( dictionary [ key ] is TOut o )
@@ -46,22 +62,32 @@ public static class LinqExtensions
4662 if ( dictionary is null || key is null )
4763 return defaultValueFunc ( ) ;
4864
49- if ( ! dictionary . ContainsKey ( key ) )
65+ if ( dictionary is ConcurrentDictionary < TKey , Task < TValue ? > > cDict )
5066 {
51- var defaultValue = defaultValueFunc ( ) ;
52- if ( defaultValue is Task < TValue ? > value )
67+ if ( ! cDict . ContainsKey ( key ) )
5368 {
54- if ( dictionary is ConcurrentDictionary < TKey , Task < TValue ? > > cDict )
55- {
69+ var defaultValue = defaultValueFunc ( ) ;
70+ if ( defaultValue is Task < TValue ? > value )
5671 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 ) )
5981 {
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 ;
6187 }
6288 }
63- return defaultValue ;
6489 }
90+
6591 return dictionary [ key ] ;
6692 }
6793
0 commit comments