SoftReferenceOptions
Allows to configure behavior of SoftReference<T>.
using System;
using System.Runtime.CompilerServices;
namespace DotNext.Runtime
{
[System.Runtime.CompilerServices.NullableContext(1)]
[System.Runtime.CompilerServices.Nullable(0)]
public class SoftReferenceOptions
{
private readonly int collectionCount;
private readonly long memoryLimit = 9223372036854775807;
public static SoftReferenceOptions Default { get; } = new SoftReferenceOptions();
public int CollectionCount {
get {
return collectionCount;
}
set {
if (value <= 0)
throw new ArgumentOutOfRangeException("value");
collectionCount = value;
}
}
public long MemoryLimit {
get {
return memoryLimit;
}
set {
if (value <= 0)
throw new ArgumentOutOfRangeException("value");
memoryLimit = value;
}
}
internal bool KeepTracking(object target)
{
int generation = GC.GetGeneration(target);
if (generation >= GC.MaxGeneration) {
if (GC.CollectionCount(generation) <= collectionCount) {
if (memoryLimit != 9223372036854775807)
return CheckMemoryLimit(generation);
return true;
}
return false;
}
return true;
}
private bool CheckMemoryLimit(int generation)
{
GCMemoryInfo gCMemoryInfo = GC.GetGCMemoryInfo();
if (gCMemoryInfo.Index != 0) {
ReadOnlySpan<GCGenerationInfo> generationInfo;
ReadOnlySpan<GCGenerationInfo> readOnlySpan = generationInfo = gCMemoryInfo.GenerationInfo;
if (readOnlySpan.Length > generation)
return generationInfo[generation].SizeAfterBytes < memoryLimit;
}
return true;
}
}
}