Skip to content

Commit 7d554db

Browse files
haipzeerhardt
authored andcommitted
Cache current process object to avoid performance hit (#5597)
* Read working set from Environment in ProcessInfo since it has better performance. * Add unit test for ProcessInfo. * Remove OSSkipCondition tag from process info unit test since it's cross-platform. * Use Environment.WorkingSet in GetMemoryUsageInBytes.
1 parent 12b8949 commit 7d554db

File tree

3 files changed

+26
-4
lines changed

3 files changed

+26
-4
lines changed

src/Libraries/Microsoft.Extensions.Diagnostics.ResourceMonitoring/Windows/Interop/ProcessInfo.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Licensed to the .NET Foundation under one or more agreements.
22
// The .NET Foundation licenses this file to you under the MIT license.
33

4+
using System;
45
using System.Diagnostics;
56
using System.Diagnostics.CodeAnalysis;
67

@@ -41,7 +42,6 @@ public ulong GetMemoryUsage()
4142

4243
public ulong GetCurrentProcessMemoryUsage()
4344
{
44-
using Process process = Process.GetCurrentProcess();
45-
return (ulong)process.WorkingSet64;
45+
return (ulong)Environment.WorkingSet;
4646
}
4747
}

src/Libraries/Microsoft.Extensions.Diagnostics.ResourceMonitoring/Windows/WindowsSnapshotProvider.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -109,8 +109,7 @@ internal static long GetCpuTicks()
109109

110110
internal static long GetMemoryUsageInBytes()
111111
{
112-
using var process = Process.GetCurrentProcess();
113-
return process.WorkingSet64;
112+
return Environment.WorkingSet;
114113
}
115114

116115
internal static ulong GetTotalMemoryInBytes()
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
4+
using Microsoft.Extensions.Diagnostics.ResourceMonitoring.Windows.Interop;
5+
using Microsoft.TestUtilities;
6+
using Xunit;
7+
8+
namespace Microsoft.Extensions.Diagnostics.ResourceMonitoring.Windows.Test;
9+
10+
/// <summary>
11+
/// Process Info Interop Tests.
12+
/// </summary>
13+
/// <remarks>These tests are added for coverage reasons, but the code doesn't have
14+
/// the necessary environment predictability to really test it.</remarks>
15+
public sealed class ProcessInfoTests
16+
{
17+
[ConditionalFact]
18+
public void GetCurrentProcessMemoryUsage()
19+
{
20+
var workingSet64 = new ProcessInfo().GetCurrentProcessMemoryUsage();
21+
Assert.True(workingSet64 > 0);
22+
}
23+
}

0 commit comments

Comments
 (0)