Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,14 @@ public override void Invoke()
{
ParseArguments();

if (StatOnly)
{
FilteredHeap.ProgressCallback = (scanned, total) =>
{
Console.WriteLine(ProgressReporter.FormatProgressMessage(scanned, total));
};
}

IEnumerable<ClrObject> objectsToPrint = FilteredHeap.EnumerateFilteredObjects(Console.CancellationToken);

bool? liveObjectWarning = null;
Expand Down
30 changes: 29 additions & 1 deletion src/Microsoft.Diagnostics.ExtensionCommands/HeapWithFilters.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,17 @@ public int? GCHeap
/// </summary>
public Func<IEnumerable<ClrSubHeap>, IOrderedEnumerable<ClrSubHeap>> SortSubHeaps { get; set; }

/// <summary>
/// Minimum interval in milliseconds between progress reports.
/// </summary>
private const int ProgressIntervalMs = 10_000;

/// <summary>
/// Optional callback invoked periodically during heap enumeration to report progress.
/// Parameters are (bytesScanned, totalBytes).
/// </summary>
public Action<long, long> ProgressCallback { get; set; }

public HeapWithFilters(ClrHeap heap)
{
_heap = heap;
Expand Down Expand Up @@ -211,7 +222,21 @@ public IEnumerable<ClrSegment> EnumerateFilteredSegments(ClrSubHeap subheap)

public IEnumerable<ClrObject> EnumerateFilteredObjects(CancellationToken cancellation)
{
foreach (ClrSegment segment in EnumerateFilteredSegments())
Action<long, long> progressCallback = ProgressCallback;
ProgressReporter progress = null;
IEnumerable<ClrSegment> segments = EnumerateFilteredSegments();

if (progressCallback != null)
{
// Materialize the segment list to avoid enumerating twice
// (once for total size, once for object enumeration).
List<ClrSegment> segmentList = segments.ToList();
long totalBytes = segmentList.Sum(s => (long)s.CommittedMemory.Length);
progress = new ProgressReporter(progressCallback, totalBytes, ProgressIntervalMs);
segments = segmentList;
}

foreach (ClrSegment segment in segments)
{
IEnumerable<ClrObject> objs;
if (MemoryRange is MemoryRange range)
Expand All @@ -235,6 +260,9 @@ public IEnumerable<ClrObject> EnumerateFilteredObjects(CancellationToken cancell
if (obj.IsValid)
{
ulong size = obj.Size;

progress?.ReportObject((long)size);

if (MinimumObjectSize != 0 && size < MinimumObjectSize)
{
continue;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@
<PackageReference Include="Microsoft.Diagnostics.Runtime" Version="$(MicrosoftDiagnosticsRuntimeVersion)" />
</ItemGroup>

<ItemGroup>
<InternalsVisibleTo Include="Microsoft.Diagnostics.ExtensionCommands.UnitTests" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="$(MSBuildThisFileDirectory)..\Microsoft.Diagnostics.DebugServices\Microsoft.Diagnostics.DebugServices.csproj" />
<ProjectReference Include="$(MSBuildThisFileDirectory)..\Microsoft.SymbolStore\Microsoft.SymbolStore.csproj" />
Expand Down
65 changes: 65 additions & 0 deletions src/Microsoft.Diagnostics.ExtensionCommands/ProgressReporter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Diagnostics;

namespace Microsoft.Diagnostics.ExtensionCommands
{
/// <summary>
/// Reports progress periodically during heap enumeration based on elapsed time.
/// </summary>
internal sealed class ProgressReporter
{
private readonly Action<long, long> _callback;
private readonly long _totalBytes;
private readonly int _intervalMs;
private readonly Stopwatch _stopwatch;
private long _scannedBytes;
private long _lastReportMs;

/// <summary>
/// Creates a new ProgressReporter.
/// </summary>
/// <param name="callback">Invoked periodically with (bytesScanned, totalBytes).</param>
/// <param name="totalBytes">Total expected bytes to scan.</param>
/// <param name="intervalMs">Minimum interval in milliseconds between reports.</param>
public ProgressReporter(Action<long, long> callback, long totalBytes, int intervalMs)
{
_callback = callback ?? throw new ArgumentNullException(nameof(callback));
_totalBytes = totalBytes;
_intervalMs = intervalMs;
_stopwatch = Stopwatch.StartNew();
}

/// <summary>
/// Gets the total number of bytes scanned so far.
/// </summary>
public long ScannedBytes => _scannedBytes;

/// <summary>
/// Reports that an object of the given size has been scanned.
/// Invokes the callback if enough time has elapsed since the last report.
/// </summary>
public void ReportObject(long objectSize)
{
_scannedBytes += objectSize;

long elapsedMs = _stopwatch.ElapsedMilliseconds;
if (elapsedMs - _lastReportMs >= _intervalMs)
{
_lastReportMs = elapsedMs;
_callback(_scannedBytes, _totalBytes);
}
}

/// <summary>
/// Formats a progress message suitable for display during heap scanning.
/// </summary>
public static string FormatProgressMessage(long scannedBytes, long totalBytes)
{
double pct = totalBytes > 0 ? 100.0 * scannedBytes / totalBytes : 0;
return $"Scanning heap: {scannedBytes / (1024 * 1024):n0} MB / {totalBytes / (1024 * 1024):n0} MB ({pct:f0}%)...";
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,11 @@ public override void Invoke()
throw new DiagnosticsException("The GC heap is not in a valid state for traversal. (Use -ignoreGCState to override.)");
}

filteredHeap.ProgressCallback = (scanned, total) =>
{
Console.WriteLine(ProgressReporter.FormatProgressMessage(scanned, total));
};

VerifyHeap(filteredHeap.EnumerateFilteredObjects(Console.CancellationToken), verifySyncTable: filteredHeap.HasFilters);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="xunit" Version="2.9.3" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="$(SrcDir)Microsoft.Diagnostics.ExtensionCommands\Microsoft.Diagnostics.ExtensionCommands.csproj" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Collections.Generic;
using System.Threading;
using Xunit;

namespace Microsoft.Diagnostics.ExtensionCommands.UnitTests
{
public class ProgressReporterTests
{
[Fact]
public void ReportObject_WithZeroInterval_CallsCallbackEveryTime()
{
List<(long scanned, long total)> reports = new();

ProgressReporter reporter = new(
(scanned, total) => reports.Add((scanned, total)),
totalBytes: 1000,
intervalMs: 0);

reporter.ReportObject(100);
reporter.ReportObject(200);
reporter.ReportObject(300);

Assert.Equal(3, reports.Count);
Assert.Equal((100, 1000), reports[0]);
Assert.Equal((300, 1000), reports[1]);
Assert.Equal((600, 1000), reports[2]);
}

[Fact]
public void ReportObject_TracksScannedBytes()
{
ProgressReporter reporter = new(
(_, _) => { },
totalBytes: 1000,
intervalMs: 60_000); // long interval so callback doesn't fire after first

reporter.ReportObject(100);
Assert.Equal(100, reporter.ScannedBytes);

reporter.ReportObject(250);
Assert.Equal(350, reporter.ScannedBytes);

reporter.ReportObject(50);
Assert.Equal(400, reporter.ScannedBytes);
}

[Fact]
public void ReportObject_WithLongInterval_DoesNotFireDuringInterval()
{
int callbackCount = 0;

ProgressReporter reporter = new(
(_, _) => callbackCount++,
totalBytes: 1000,
intervalMs: 60_000); // 60 seconds - won't fire in this test

// No calls should fire within the 60s interval
for (int i = 0; i < 100; i++)
{
reporter.ReportObject(1);
}

Assert.Equal(0, callbackCount);
Assert.Equal(100, reporter.ScannedBytes);
}

[Fact]
public void FormatProgressMessage_FormatsCorrectly()
{
string msg = ProgressReporter.FormatProgressMessage(
scannedBytes: 5L * 1024 * 1024 * 1024, // 5 GB
totalBytes: 16L * 1024 * 1024 * 1024); // 16 GB

Assert.Contains("5", msg);
Assert.Contains("16", msg);
Assert.Contains("31%", msg);
Assert.Contains("Scanning heap:", msg);
}

[Fact]
public void FormatProgressMessage_HandlesZeroTotal()
{
string msg = ProgressReporter.FormatProgressMessage(0, 0);
Assert.Contains("0%", msg);
}

[Fact]
public void FormatProgressMessage_Handles100Percent()
{
string msg = ProgressReporter.FormatProgressMessage(1024 * 1024, 1024 * 1024);
Assert.Contains("100%", msg);
}
}
}
Loading