File tree Expand file tree Collapse file tree 2 files changed +4
-29
lines changed
src/Agent/NewRelic/Agent/Extensions/NewRelic.Agent.Extensions/Caching
tests/Agent/UnitTests/NewRelic.Agent.Extensions.Tests/Cache Expand file tree Collapse file tree 2 files changed +4
-29
lines changed Original file line number Diff line number Diff line change @@ -11,35 +11,28 @@ namespace NewRelic.Agent.Extensions.Caching
11
11
/// <typeparam name="T"></typeparam>
12
12
public class WeakReferenceKey < T > where T : class
13
13
{
14
+ private readonly int _hashCode ;
14
15
private WeakReference < T > WeakReference { get ; }
15
16
16
17
public WeakReferenceKey ( T cacheKey )
17
18
{
18
19
WeakReference = new WeakReference < T > ( cacheKey ) ;
20
+ _hashCode = cacheKey . GetHashCode ( ) ; // store the hashcode since we use it in the Equals method and the object could have been GC'd by the time we need to look for it
19
21
}
20
22
21
23
public override bool Equals ( object obj )
22
24
{
23
25
if ( obj is WeakReferenceKey < T > otherKey )
24
26
{
25
- if ( WeakReference . TryGetTarget ( out var thisTarget ) &&
26
- otherKey . WeakReference . TryGetTarget ( out var otherTarget ) )
27
- {
28
- return ReferenceEquals ( thisTarget , otherTarget ) ;
29
- }
27
+ return otherKey . GetHashCode ( ) == _hashCode ;
30
28
}
31
29
32
30
return false ;
33
31
}
34
32
35
33
public override int GetHashCode ( )
36
34
{
37
- if ( WeakReference . TryGetTarget ( out var target ) )
38
- {
39
- return target . GetHashCode ( ) ;
40
- }
41
-
42
- return 0 ;
35
+ return _hashCode ;
43
36
}
44
37
45
38
/// <summary>
Original file line number Diff line number Diff line change @@ -93,24 +93,6 @@ public void GetHashCode_ShouldReturnDifferentHashCodeForDifferentObjects()
93
93
Assert . That ( hashCode1 , Is . Not . EqualTo ( hashCode2 ) ) ;
94
94
}
95
95
96
- [ Test ]
97
- public async Task GetHashCode_ShouldReturnZeroIfTargetIsGarbageCollected ( )
98
- {
99
- // Arrange
100
- var weakRefKey = GetWeakReferenceKey ( ) ;
101
-
102
- // Act
103
- Assert . That ( weakRefKey . Value , Is . Not . Null ) ;
104
- // force garbage collection
105
- GC . Collect ( ) ;
106
- GC . WaitForPendingFinalizers ( ) ;
107
- await Task . Delay ( 500 ) ;
108
- GC . Collect ( ) ; // Force another collection
109
-
110
- // Assert
111
- Assert . That ( weakRefKey . GetHashCode ( ) , Is . EqualTo ( 0 ) ) ;
112
- }
113
-
114
96
[ Test ]
115
97
public async Task Value_ShouldReturnNullIfTargetIsGarbageCollected ( )
116
98
{
You can’t perform that action at this time.
0 commit comments