File tree Expand file tree Collapse file tree 2 files changed +28
-1
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 +28
-1
lines changed Original file line number Diff line number Diff line change @@ -24,6 +24,13 @@ public override bool Equals(object obj)
24
24
{
25
25
if ( obj is WeakReferenceKey < T > otherKey )
26
26
{
27
+ if ( WeakReference . TryGetTarget ( out var thisTarget ) &&
28
+ otherKey . WeakReference . TryGetTarget ( out var otherTarget ) )
29
+ {
30
+ return ReferenceEquals ( thisTarget , otherTarget ) ;
31
+ }
32
+
33
+ // if one of the targets has been garbage collected, we can still compare the hashcodes
27
34
return otherKey . GetHashCode ( ) == _hashCode ;
28
35
}
29
36
@@ -32,7 +39,7 @@ public override bool Equals(object obj)
32
39
33
40
public override int GetHashCode ( )
34
41
{
35
- return _hashCode ;
42
+ return WeakReference . TryGetTarget ( out var target ) ? target . GetHashCode ( ) : _hashCode ;
36
43
}
37
44
38
45
/// <summary>
Original file line number Diff line number Diff line change @@ -150,6 +150,26 @@ public async Task Equals_ShouldReturnFalseIfTargetIsGarbageCollected()
150
150
Assert . That ( weakRefKey1 . Equals ( weakRefKey2 ) , Is . False ) ;
151
151
}
152
152
153
+ [ Test ]
154
+ public async Task GetHashCode_ShouldReturnOriginalHashcodeIfTargetIsGarbageCollected ( )
155
+ {
156
+ // Arrange
157
+ var weakRefKey = GetWeakReferenceKey ( ) ;
158
+ var originalHashCode = weakRefKey . GetHashCode ( ) ;
159
+
160
+ // Act
161
+ Assert . That ( weakRefKey . Value , Is . Not . Null ) ;
162
+
163
+ // force garbage collection
164
+ GC . Collect ( ) ;
165
+ GC . WaitForPendingFinalizers ( ) ;
166
+ await Task . Delay ( 500 ) ;
167
+ GC . Collect ( ) ; // Force another collection
168
+
169
+ // Assert
170
+ Assert . That ( weakRefKey . Value , Is . Null ) ; // ensure GC really happened
171
+ Assert . That ( weakRefKey . GetHashCode ( ) , Is . EqualTo ( originalHashCode ) ) ;
172
+ }
153
173
private class Foo
154
174
{
155
175
public string Bar { get ; set ; }
You can’t perform that action at this time.
0 commit comments