Skip to content

Commit f1a5a9c

Browse files
committed
Fixed WeakReferenceKey to use hashcode for comparisons
1 parent d242c8e commit f1a5a9c

File tree

2 files changed

+4
-29
lines changed

2 files changed

+4
-29
lines changed

src/Agent/NewRelic/Agent/Extensions/NewRelic.Agent.Extensions/Caching/WeakReferenceKey.cs

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -11,35 +11,28 @@ namespace NewRelic.Agent.Extensions.Caching
1111
/// <typeparam name="T"></typeparam>
1212
public class WeakReferenceKey<T> where T : class
1313
{
14+
private readonly int _hashCode;
1415
private WeakReference<T> WeakReference { get; }
1516

1617
public WeakReferenceKey(T cacheKey)
1718
{
1819
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
1921
}
2022

2123
public override bool Equals(object obj)
2224
{
2325
if (obj is WeakReferenceKey<T> otherKey)
2426
{
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;
3028
}
3129

3230
return false;
3331
}
3432

3533
public override int GetHashCode()
3634
{
37-
if (WeakReference.TryGetTarget(out var target))
38-
{
39-
return target.GetHashCode();
40-
}
41-
42-
return 0;
35+
return _hashCode;
4336
}
4437

4538
/// <summary>

tests/Agent/UnitTests/NewRelic.Agent.Extensions.Tests/Cache/WeakReferenceKeyTests.cs

Lines changed: 0 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -93,24 +93,6 @@ public void GetHashCode_ShouldReturnDifferentHashCodeForDifferentObjects()
9393
Assert.That(hashCode1, Is.Not.EqualTo(hashCode2));
9494
}
9595

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-
11496
[Test]
11597
public async Task Value_ShouldReturnNullIfTargetIsGarbageCollected()
11698
{

0 commit comments

Comments
 (0)