Skip to content

Commit

Permalink
Reworked WeakReferenceKey.Equals()
Browse files Browse the repository at this point in the history
  • Loading branch information
tippmar-nr committed Feb 4, 2025
1 parent f1a5a9c commit 36ca20d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,13 @@ public override bool Equals(object obj)
{
if (obj is WeakReferenceKey<T> otherKey)
{
if (WeakReference.TryGetTarget(out var thisTarget) &&
otherKey.WeakReference.TryGetTarget(out var otherTarget))
{
return ReferenceEquals(thisTarget, otherTarget);
}

// if one of the targets has been garbage collected, we can still compare the hashcodes
return otherKey.GetHashCode() == _hashCode;
}

Expand All @@ -32,7 +39,7 @@ public override bool Equals(object obj)

public override int GetHashCode()
{
return _hashCode;
return WeakReference.TryGetTarget(out var target) ? target.GetHashCode() : _hashCode;
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,26 @@ public async Task Equals_ShouldReturnFalseIfTargetIsGarbageCollected()
Assert.That(weakRefKey1.Equals(weakRefKey2), Is.False);
}

[Test]
public async Task GetHashCode_ShouldReturnOriginalHashcodeIfTargetIsGarbageCollected()
{
// Arrange
var weakRefKey = GetWeakReferenceKey();
var originalHashCode = weakRefKey.GetHashCode();

// Act
Assert.That(weakRefKey.Value, Is.Not.Null);

// force garbage collection
GC.Collect();
GC.WaitForPendingFinalizers();
await Task.Delay(500);
GC.Collect(); // Force another collection

// Assert
Assert.That(weakRefKey.Value, Is.Null); // ensure GC really happened
Assert.That(weakRefKey.GetHashCode(), Is.EqualTo(originalHashCode));
}
private class Foo
{
public string Bar { get; set; }
Expand Down

0 comments on commit 36ca20d

Please sign in to comment.