-
-
Notifications
You must be signed in to change notification settings - Fork 213
/
Copy pathGarbageCollectionMonitor.cs
39 lines (35 loc) · 1.33 KB
/
GarbageCollectionMonitor.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
using Sentry.Extensibility;
namespace Sentry.Internal;
/// <summary>
/// Simple class to detect when Full Garbage Collection occurs
/// </summary>
internal sealed class GarbageCollectionMonitor
{
private const int MaxGenerationThreshold = 10;
private const int LargeObjectHeapThreshold = 10;
public static Task Start(Action onGarbageCollected, CancellationToken cancellationToken, IGCImplementation? gc = null) =>
Task.Run(() => MonitorGarbageCollection(onGarbageCollected, cancellationToken, gc), cancellationToken);
private static void MonitorGarbageCollection(Action onGarbageCollected, CancellationToken cancellationToken, IGCImplementation? gc = null)
{
gc ??= new SystemGCImplementation();
try
{
gc.RegisterForFullGCNotification(MaxGenerationThreshold, LargeObjectHeapThreshold);
while (!cancellationToken.IsCancellationRequested)
{
if (gc.WaitForFullGCComplete(TimeSpan.FromSeconds(1)) == GCNotificationStatus.Succeeded)
{
onGarbageCollected?.Invoke();
}
}
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
// Ignore
}
finally
{
gc.CancelFullGCNotification();
}
}
}