Improve low-impact runtime behavior

This commit is contained in:
PrimeBuild-pc
2026-05-16 19:56:13 +02:00
parent 66cae4556c
commit fd20661bb1
13 changed files with 356 additions and 9 deletions
+32 -1
View File
@@ -31,6 +31,7 @@ namespace ThreadPilot
using System.Windows.Media.Imaging;
using Microsoft.Extensions.DependencyInjection;
using ThreadPilot.Helpers;
using ThreadPilot.Models;
using ThreadPilot.Services;
using ThreadPilot.ViewModels;
using ThreadPilot.Views;
@@ -1105,7 +1106,13 @@ namespace ThreadPilot
}
};
this.systemTrayUpdateTimer.AutoReset = true;
this.systemTrayUpdateTimer.Start();
if (!this.isSystemTrayUpdatesSuspended &&
this.IsVisible &&
this.WindowState != WindowState.Minimized)
{
this.systemTrayUpdateTimer.Start();
}
}
catch (Exception ex)
{
@@ -1259,6 +1266,7 @@ namespace ThreadPilot
this.mainWindowViewModel.IsDarkTheme = useDarkTheme;
this.systemTrayService.ApplyTheme(useDarkTheme);
DwmHelper.ApplyWindowCaptionTheme(this, useDarkTheme);
this.ApplySelfResourcePolicy(this.lastAppliedRefreshState ?? this.GetForegroundActivityState(), e.NewSettings);
}
private void OnMonitoringStatusChanged(object? sender, MonitoringStatusEventArgs e)
@@ -1366,6 +1374,13 @@ namespace ThreadPilot
private void ApplyAppRefreshPolicy(AppActivityState state)
{
if (!AppRefreshPolicy.ShouldApplyTransition(this.lastAppliedRefreshState, state))
{
return;
}
this.lastAppliedRefreshState = state;
var decision = AppRefreshPolicy.Evaluate(state);
var isHiddenState = state is AppActivityState.Minimized or AppActivityState.TrayHidden;
var isProcessViewActive = state == AppActivityState.ForegroundProcessView;
@@ -1401,6 +1416,22 @@ namespace ThreadPilot
{
_ = this.performanceViewModel.SuspendBackgroundMonitoringAsync();
}
this.ApplySelfResourcePolicy(state);
}
private void ApplySelfResourcePolicy(AppActivityState state, ApplicationSettingsModel? settings = null)
{
var currentSettings = settings ?? this.settingsService.Settings;
var isHiddenState = state is AppActivityState.Minimized or AppActivityState.TrayHidden;
if (isHiddenState && currentSettings.EnableSelfLowImpactMode)
{
this.selfResourceManagementService.ApplyLowImpactMode(currentSettings.EnableSelfAffinityLimit);
return;
}
this.selfResourceManagementService.RestoreForegroundMode();
}
protected override void OnSourceInitialized(EventArgs e)
+4 -1
View File
@@ -54,6 +54,7 @@ namespace ThreadPilot
private readonly SettingsViewModel settingsViewModel;
private readonly MainWindowViewModel mainWindowViewModel;
private readonly SystemTweaksViewModel systemTweaksViewModel;
private readonly ISelfResourceManagementService selfResourceManagementService;
private readonly IKeyboardShortcutService keyboardShortcutService;
private readonly IServiceProvider serviceProvider;
private readonly IThemeService themeService;
@@ -61,6 +62,7 @@ namespace ThreadPilot
private bool isSystemTrayUpdatesSuspended;
private int isSystemTrayUpdateInProgress;
private int systemTrayUpdateFailureStreak;
private AppActivityState? lastAppliedRefreshState;
private readonly IElevationService elevationService;
private readonly ISecurityService securityService;
@@ -93,6 +95,7 @@ namespace ThreadPilot
SettingsViewModel settingsViewModel,
MainWindowViewModel mainWindowViewModel,
SystemTweaksViewModel systemTweaksViewModel,
ISelfResourceManagementService selfResourceManagementService,
IKeyboardShortcutService keyboardShortcutService,
IThemeService themeService,
IServiceProvider serviceProvider,
@@ -125,6 +128,7 @@ namespace ThreadPilot
this.settingsViewModel = settingsViewModel;
this.mainWindowViewModel = mainWindowViewModel;
this.systemTweaksViewModel = systemTweaksViewModel;
this.selfResourceManagementService = selfResourceManagementService;
this.keyboardShortcutService = keyboardShortcutService;
this.themeService = themeService;
this.serviceProvider = serviceProvider;
@@ -156,4 +160,3 @@ namespace ThreadPilot
}
}
}
+8
View File
@@ -171,6 +171,12 @@ namespace ThreadPilot.Models
[ObservableProperty]
private bool hasSeenElevationWarning = false;
[ObservableProperty]
private bool enableSelfLowImpactMode = false;
[ObservableProperty]
private bool enableSelfAffinityLimit = false;
[ObservableProperty]
private int maxLogFileSizeMb = 10;
@@ -243,6 +249,8 @@ namespace ThreadPilot.Models
this.EnablePerformanceCounters = other.EnablePerformanceCounters;
this.HasSeenPerformanceIntro = other.HasSeenPerformanceIntro;
this.HasSeenElevationWarning = other.HasSeenElevationWarning;
this.EnableSelfLowImpactMode = other.EnableSelfLowImpactMode;
this.EnableSelfAffinityLimit = other.EnableSelfAffinityLimit;
this.MaxLogFileSizeMb = other.MaxLogFileSizeMb;
this.LogRetentionDays = other.LogRetentionDays;
+5
View File
@@ -43,6 +43,11 @@ namespace ThreadPilot.Services
/// </summary>
public static class AppRefreshPolicy
{
public static bool ShouldApplyTransition(AppActivityState? previousState, AppActivityState nextState)
{
return previousState != nextState;
}
public static AppRefreshDecision Evaluate(AppActivityState state)
{
return state switch
@@ -0,0 +1,25 @@
/*
* ThreadPilot - Advanced Windows Process and Power Plan Manager
* Copyright (C) 2025 Prime Build
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3 only.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
namespace ThreadPilot.Services
{
public interface ISelfResourceManagementService
{
void ApplyLowImpactMode(bool limitAffinity);
void RestoreForegroundMode();
}
}
+208
View File
@@ -0,0 +1,208 @@
/*
* ThreadPilot - Advanced Windows Process and Power Plan Manager
* Copyright (C) 2025 Prime Build
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3 only.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
namespace ThreadPilot.Services
{
using System;
using System.ComponentModel;
using System.Diagnostics;
using Microsoft.Extensions.Logging;
public static class SelfResourcePolicy
{
public static bool TryCreateLowImpactAffinityMask(int logicalProcessorCount, out long affinityMask)
{
affinityMask = 0;
if (logicalProcessorCount <= 2 || logicalProcessorCount >= 64)
{
return false;
}
var selectedProcessorCount = logicalProcessorCount >= 4 ? 2 : 1;
for (var index = logicalProcessorCount - selectedProcessorCount; index < logicalProcessorCount; index++)
{
affinityMask |= 1L << index;
}
return affinityMask != 0;
}
}
public sealed class SelfResourceManagementService : ISelfResourceManagementService
{
private readonly ILogger<SelfResourceManagementService> logger;
private readonly object syncRoot = new();
private ProcessPriorityClass? originalPriority;
private IntPtr? originalAffinity;
private bool priorityLowered;
private bool affinityConstrained;
public SelfResourceManagementService(ILogger<SelfResourceManagementService> logger)
{
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public void ApplyLowImpactMode(bool limitAffinity)
{
lock (this.syncRoot)
{
this.TryLowerPriority();
if (limitAffinity)
{
this.TryConstrainAffinity();
return;
}
this.TryRestoreAffinity();
}
}
public void RestoreForegroundMode()
{
lock (this.syncRoot)
{
this.TryRestoreAffinity();
this.TryRestorePriority();
}
}
private void TryLowerPriority()
{
if (this.priorityLowered)
{
return;
}
try
{
using var process = Process.GetCurrentProcess();
var currentPriority = process.PriorityClass;
if (!ShouldLowerPriority(currentPriority))
{
return;
}
this.originalPriority = currentPriority;
process.PriorityClass = ProcessPriorityClass.BelowNormal;
this.priorityLowered = true;
this.logger.LogDebug("Lowered ThreadPilot priority from {OriginalPriority} to BelowNormal", currentPriority);
}
catch (Win32Exception ex)
{
this.logger.LogDebug(ex, "Windows blocked ThreadPilot self-priority lowering");
}
catch (Exception ex)
{
this.logger.LogDebug(ex, "Failed to lower ThreadPilot priority");
}
}
private void TryConstrainAffinity()
{
if (this.affinityConstrained)
{
return;
}
try
{
if (!SelfResourcePolicy.TryCreateLowImpactAffinityMask(Environment.ProcessorCount, out var candidateMask))
{
return;
}
using var process = Process.GetCurrentProcess();
var currentAffinity = process.ProcessorAffinity;
var effectiveMask = candidateMask & currentAffinity.ToInt64();
if (effectiveMask == 0 || effectiveMask == currentAffinity.ToInt64())
{
return;
}
this.originalAffinity = currentAffinity;
process.ProcessorAffinity = new IntPtr(effectiveMask);
this.affinityConstrained = true;
this.logger.LogDebug("Constrained ThreadPilot affinity from 0x{OriginalAffinity:X} to 0x{LowImpactAffinity:X}", currentAffinity.ToInt64(), effectiveMask);
}
catch (Win32Exception ex)
{
this.logger.LogDebug(ex, "Windows blocked ThreadPilot self-affinity limiting");
}
catch (Exception ex)
{
this.logger.LogDebug(ex, "Failed to constrain ThreadPilot affinity");
}
}
private void TryRestoreAffinity()
{
if (!this.affinityConstrained || this.originalAffinity == null)
{
return;
}
try
{
using var process = Process.GetCurrentProcess();
process.ProcessorAffinity = this.originalAffinity.Value;
this.logger.LogDebug("Restored ThreadPilot affinity to 0x{OriginalAffinity:X}", this.originalAffinity.Value.ToInt64());
}
catch (Exception ex)
{
this.logger.LogDebug(ex, "Failed to restore ThreadPilot affinity");
}
finally
{
this.affinityConstrained = false;
this.originalAffinity = null;
}
}
private void TryRestorePriority()
{
if (!this.priorityLowered || this.originalPriority == null)
{
return;
}
try
{
using var process = Process.GetCurrentProcess();
process.PriorityClass = this.originalPriority.Value;
this.logger.LogDebug("Restored ThreadPilot priority to {OriginalPriority}", this.originalPriority.Value);
}
catch (Exception ex)
{
this.logger.LogDebug(ex, "Failed to restore ThreadPilot priority");
}
finally
{
this.priorityLowered = false;
this.originalPriority = null;
}
}
private static bool ShouldLowerPriority(ProcessPriorityClass priority)
{
return priority is ProcessPriorityClass.Normal
or ProcessPriorityClass.AboveNormal
or ProcessPriorityClass.High
or ProcessPriorityClass.RealTime;
}
}
}
+1
View File
@@ -147,6 +147,7 @@ namespace ThreadPilot.Services
// Application configuration and settings
services.AddSingleton<IApplicationSettingsService, ApplicationSettingsService>();
services.AddSingleton<IThemeService, ThemeService>();
services.AddSingleton<ISelfResourceManagementService, SelfResourceManagementService>();
// User interface services
services.AddSingleton<INotificationService, NotificationService>();
+5
View File
@@ -378,6 +378,11 @@ namespace ThreadPilot.Services
public void ApplyTheme(bool useDarkTheme)
{
if (this.isDarkTheme == useDarkTheme)
{
return;
}
this.isDarkTheme = useDarkTheme;
this.ApplyContextMenuTheme();
}
+8
View File
@@ -51,6 +51,14 @@ namespace ThreadPilot.Services
try
{
if (this.IsDarkTheme == useDarkTheme &&
this.activeThemeDictionary?.Source?.OriginalString != null &&
string.Equals(this.activeThemeDictionary.Source.OriginalString, targetUri.OriginalString, StringComparison.OrdinalIgnoreCase) &&
appResources.MergedDictionaries.Contains(this.activeThemeDictionary))
{
return;
}
for (int i = appResources.MergedDictionaries.Count - 1; i >= 0; i--)
{
var dictionary = appResources.MergedDictionaries[i];
@@ -40,5 +40,21 @@ namespace ThreadPilot.Core.Tests
Assert.False(decision.PowerPlanUiRefreshEnabled);
Assert.True(decision.BackgroundAutomationEnabled);
}
[Theory]
[InlineData(null, AppActivityState.ForegroundProcessView, true)]
[InlineData(AppActivityState.ForegroundProcessView, AppActivityState.ForegroundProcessView, false)]
[InlineData(AppActivityState.ForegroundOtherTab, AppActivityState.ForegroundOtherTab, false)]
[InlineData(AppActivityState.Minimized, AppActivityState.Minimized, false)]
[InlineData(AppActivityState.TrayHidden, AppActivityState.TrayHidden, false)]
[InlineData(AppActivityState.TrayHidden, AppActivityState.ForegroundProcessView, true)]
[InlineData(AppActivityState.ForegroundProcessView, AppActivityState.ForegroundOtherTab, true)]
public void ShouldApplyTransition_SkipsRedundantStateTransitions(
AppActivityState? previousState,
AppActivityState nextState,
bool expected)
{
Assert.Equal(expected, AppRefreshPolicy.ShouldApplyTransition(previousState, nextState));
}
}
}
@@ -0,0 +1,37 @@
namespace ThreadPilot.Core.Tests
{
using ThreadPilot.Services;
public sealed class SelfResourcePolicyTests
{
[Theory]
[InlineData(1)]
[InlineData(2)]
public void TryCreateLowImpactAffinityMask_DisablesAffinityOnSmallSystems(int logicalProcessorCount)
{
Assert.False(SelfResourcePolicy.TryCreateLowImpactAffinityMask(logicalProcessorCount, out _));
}
[Theory]
[InlineData(3, 0b100)]
[InlineData(4, 0b1100)]
[InlineData(8, 0b1100_0000)]
public void TryCreateLowImpactAffinityMask_UsesLastLogicalProcessors(
int logicalProcessorCount,
long expectedMask)
{
Assert.True(SelfResourcePolicy.TryCreateLowImpactAffinityMask(logicalProcessorCount, out var mask));
Assert.Equal(expectedMask, mask);
}
[Theory]
[InlineData(0)]
[InlineData(-1)]
[InlineData(64)]
[InlineData(128)]
public void TryCreateLowImpactAffinityMask_RejectsInvalidProcessorCounts(int logicalProcessorCount)
{
Assert.False(SelfResourcePolicy.TryCreateLowImpactAffinityMask(logicalProcessorCount, out _));
}
}
}
+4 -4
View File
@@ -16,10 +16,10 @@
<TrimMode>link</TrimMode>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<NoWarn>CS1998;CS0067;CS0414;WFAC010;IL3000;MVVMTK0034</NoWarn>
<Version>1.1.4</Version>
<AssemblyVersion>1.1.4.0</AssemblyVersion>
<FileVersion>1.1.4.0</FileVersion>
<InformationalVersion>1.1.4</InformationalVersion>
<Version>1.1.5</Version>
<AssemblyVersion>1.1.5.0</AssemblyVersion>
<FileVersion>1.1.5.0</FileVersion>
<InformationalVersion>1.1.5</InformationalVersion>
</PropertyGroup>
<ItemGroup>
+3 -3
View File
@@ -34,7 +34,7 @@ namespace ThreadPilot.ViewModels
{
private readonly IPowerPlanService powerPlanService;
private System.Timers.Timer? refreshTimer;
private bool isAutoRefreshPaused;
private bool isAutoRefreshPaused = true;
private int isRefreshInProgress;
[ObservableProperty]
@@ -97,7 +97,6 @@ namespace ThreadPilot.ViewModels
Interlocked.Exchange(ref this.isRefreshInProgress, 0);
}
};
this.refreshTimer.Start();
}
public void PauseAutoRefresh()
@@ -108,10 +107,11 @@ namespace ThreadPilot.ViewModels
public void ResumeAutoRefresh(bool refreshImmediately = true)
{
var wasPaused = this.isAutoRefreshPaused;
this.isAutoRefreshPaused = false;
this.refreshTimer?.Start();
if (!refreshImmediately)
if (!refreshImmediately || !wasPaused)
{
return;
}