Skip to content

Free, open-source Windows optimization tool for performance, privacy, and simplicity.

perf: optimize startup preloading, async execution and UI responsiveness

fatDuckc4f2f5082ab3
diff --git a/optimizerDuck/App.xaml.cs b/optimizerDuck/App.xaml.cs
index 9e403b2..ba477f7 100644
--- a/optimizerDuck/App.xaml.cs
+++ b/optimizerDuck/App.xaml.cs
@@ -405,12 +405,13 @@ public partial class App : Application
mainWindow.Show();
});
- _logger.LogInformation("Preloading optimizations...");
- await optimizationRegistry.PreloadOptimizationsAsync().ConfigureAwait(false);
-
- _logger.LogInformation("Preloading customize settings...");
+ _logger.LogInformation("Preloading optimizations and customize settings...");
var customizeRegistry = _host.Services.GetRequiredService<CustomizeRegistry>();
- await customizeRegistry.PreloadCategoriesAsync().ConfigureAwait(false);
+ await Task.WhenAll(
+ optimizationRegistry.PreloadOptimizationsAsync(),
+ customizeRegistry.PreloadCategoriesAsync()
+ )
+ .ConfigureAwait(false);
RevertManager.RemoveOrphanedTempFiles(_logger);
}
diff --git a/optimizerDuck/Services/Customize/CustomizeRegistry.cs b/optimizerDuck/Services/Customize/CustomizeRegistry.cs
index 2db6762..1ffe220 100644
--- a/optimizerDuck/Services/Customize/CustomizeRegistry.cs
+++ b/optimizerDuck/Services/Customize/CustomizeRegistry.cs
@@ -28,29 +28,49 @@ public class CustomizeRegistry
/// </summary>
public bool IsPreloaded { get; private set; }
+ private readonly Lock _preloadLock = new();
+ private Task? _preloadTask;
+
/// <summary>
/// Ensures categories have been discovered before the customize UI binds.
/// Concurrent callers share a single discovery; a failed discovery is retried.
/// </summary>
- public async Task EnsurePreloadedAsync()
+ public Task EnsurePreloadedAsync()
{
if (IsPreloaded)
- return;
+ return Task.CompletedTask;
- _preloadTask ??= PreloadCategoriesAsync();
- try
+ Task task;
+ lock (_preloadLock)
{
- await _preloadTask.ConfigureAwait(false);
+ if (IsPreloaded)
+ return Task.CompletedTask;
+ _preloadTask ??= PreloadCategoriesAsync();
+ task = _preloadTask;
}
- finally
+
+ return AwaitPreloadAsync(task);
+
+ async Task AwaitPreloadAsync(Task t)
{
- if (!IsPreloaded)
- _preloadTask = null;
+ try
+ {
+ await t.ConfigureAwait(false);
+ }
+ finally
+ {
+ if (!IsPreloaded)
+ {
+ lock (_preloadLock)
+ {
+ if (!IsPreloaded && ReferenceEquals(_preloadTask, t))
+ _preloadTask = null;
+ }
+ }
+ }
}
}
- private Task? _preloadTask;
-
/// <summary>Discovers the customize categories and their settings by reflection.</summary>
public async Task PreloadCategoriesAsync()
{
diff --git a/optimizerDuck/Services/Optimization/OperationRunner.cs b/optimizerDuck/Services/Optimization/OperationRunner.cs
index 87893d2..e032e23 100644
--- a/optimizerDuck/Services/Optimization/OperationRunner.cs
+++ b/optimizerDuck/Services/Optimization/OperationRunner.cs
@@ -88,6 +88,19 @@ public class OperationRunner(
? null
: applyResult.ErrorMessage;
}
+ catch (OperationCanceledException ocex)
+ {
+ _logger.LogInformation("Operation {Name} was cancelled", request.Subject.LogName);
+ return new OptimizationResult
+ {
+ Status = changes.ModifiedSystem
+ ? OptimizationSuccessResult.PartialSuccess
+ : OptimizationSuccessResult.Failed,
+ Message = Loc.Instance["Common.OperationCancelled"],
+ Exception = ocex,
+ FailedSteps = changes.FailedSteps.OrderBy(s => s.Index).ToList(),
+ };
+ }
catch (Exception ex)
{
exception = ex;
diff --git a/optimizerDuck/Services/Optimization/OptimizationRegistry.cs b/optimizerDuck/Services/Optimization/OptimizationRegistry.cs
index fbdc6c5..bd0b849 100644
--- a/optimizerDuck/Services/Optimization/OptimizationRegistry.cs
+++ b/optimizerDuck/Services/Optimization/OptimizationRegistry.cs
@@ -21,29 +21,49 @@ public class OptimizationRegistry(ILoggerFactory loggerFactory)
/// </summary>
public bool IsPreloaded { get; private set; }
+ private readonly Lock _preloadLock = new();
+ private Task? _preloadTask;
+
/// <summary>
/// Ensures categories and applied-state are loaded before the optimize UI binds.
/// Concurrent callers share a single discovery; a failed discovery is retried.
/// </summary>
- public async Task EnsurePreloadedAsync()
+ public Task EnsurePreloadedAsync()
{
if (IsPreloaded)
- return;
+ return Task.CompletedTask;
- _preloadTask ??= PreloadOptimizationsAsync();
- try
+ Task task;
+ lock (_preloadLock)
{
- await _preloadTask.ConfigureAwait(false);
+ if (IsPreloaded)
+ return Task.CompletedTask;
+ _preloadTask ??= PreloadOptimizationsAsync();
+ task = _preloadTask;
}
- finally
+
+ return AwaitPreloadAsync(task);
+
+ async Task AwaitPreloadAsync(Task t)
{
- if (!IsPreloaded)
- _preloadTask = null;
+ try
+ {
+ await t.ConfigureAwait(false);
+ }
+ finally
+ {
+ if (!IsPreloaded)
+ {
+ lock (_preloadLock)
+ {
+ if (!IsPreloaded && ReferenceEquals(_preloadTask, t))
+ _preloadTask = null;
+ }
+ }
+ }
}
}
- private Task? _preloadTask;
-
/// <summary>
/// Discovers the optimization categories by reflection and loads the applied state of
/// their optimizations from revert data on disk.
diff --git a/optimizerDuck/Services/Optimization/OptimizationService.cs b/optimizerDuck/Services/Optimization/OptimizationService.cs
index dfff680..0788c51 100644
--- a/optimizerDuck/Services/Optimization/OptimizationService.cs
+++ b/optimizerDuck/Services/Optimization/OptimizationService.cs
@@ -288,27 +288,38 @@ public class OptimizationService(
// Applied state comes from the presence of revert data, not from a database, and a
// file that cannot be read still counts as data, so an item is never offered for a
// fresh apply while an old payload is still sitting next to it.
- foreach (var opt in optimizations)
- {
- var applied = await RevertManager.IsAppliedAsync(opt.Id).ConfigureAwait(false);
- opt.State.IsApplied = applied;
- opt.State.AppliedAt = applied
- ? (await RevertManager.GetRevertDataAsync(opt.Id).ConfigureAwait(false))?.AppliedAt
- : null;
-
- // The record outlives the revert file, so it is read separately and never gates the
- // applied mark.
- var record = ChangeRecordStore.TryRead(opt.Id);
- opt.State.AppliedSummary = record is null
- ? string.Empty
- : Loc.Instance[
- "Optimizer.UI.State.Applied.Summary",
- record.ChangedCount,
- record.CountOf(ChangeKind.Skip),
- record.CountOf(ChangeKind.NotApplicable),
- record.CountOf(ChangeKind.Refused)
- ];
- }
+ await Parallel
+ .ForEachAsync(
+ optimizations,
+ new ParallelOptions
+ {
+ MaxDegreeOfParallelism = Math.Clamp(Environment.ProcessorCount, 2, 8),
+ },
+ async (opt, _) =>
+ {
+ var applied = await RevertManager.IsAppliedAsync(opt.Id).ConfigureAwait(false);
+ opt.State.IsApplied = applied;
+ opt.State.AppliedAt = applied
+ ? (
+ await RevertManager.GetRevertDataAsync(opt.Id).ConfigureAwait(false)
+ )?.AppliedAt
+ : null;
+
+ // The record outlives the revert file, so it is read separately and never gates the
+ // applied mark.
+ var record = ChangeRecordStore.TryRead(opt.Id);
+ opt.State.AppliedSummary = record is null
+ ? string.Empty
+ : Loc.Instance[
+ "Optimizer.UI.State.Applied.Summary",
+ record.ChangedCount,
+ record.CountOf(ChangeKind.Skip),
+ record.CountOf(ChangeKind.NotApplicable),
+ record.CountOf(ChangeKind.Refused)
+ ];
+ }
+ )
+ .ConfigureAwait(false);
}
/// <summary>
diff --git a/optimizerDuck/Services/System/Primitives/ProcessRunner.cs b/optimizerDuck/Services/System/Primitives/ProcessRunner.cs
index d2525e8..b52ae5e 100644
--- a/optimizerDuck/Services/System/Primitives/ProcessRunner.cs
+++ b/optimizerDuck/Services/System/Primitives/ProcessRunner.cs
@@ -145,8 +145,10 @@ public sealed class ProcessRunner
);
try
{
- process.WaitForExit(GraceDrainMs);
+ using var graceCts = new CancellationTokenSource(GraceDrainMs);
+ await process.WaitForExitAsync(graceCts.Token).ConfigureAwait(false);
}
+ catch (OperationCanceledException) { }
catch (Exception ex)
{
_logger?.LogError(
@@ -165,11 +167,15 @@ public sealed class ProcessRunner
TryKill(process, pid, "force kill");
try
{
- if (!process.WaitForExit(ForceKillWaitMs))
- _logger?.LogWarning(
- "Process did not exit after force kill: PID {ProcessId}. User may need manual cleanup.",
- pid
- );
+ using var forceCts = new CancellationTokenSource(ForceKillWaitMs);
+ await process.WaitForExitAsync(forceCts.Token).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException)
+ {
+ _logger?.LogWarning(
+ "Process did not exit after force kill: PID {ProcessId}. User may need manual cleanup.",
+ pid
+ );
}
catch (Exception ex)
{
diff --git a/optimizerDuck/Services/UI/BloatwareService.cs b/optimizerDuck/Services/UI/BloatwareService.cs
index 7ade148..a7793ab 100644
--- a/optimizerDuck/Services/UI/BloatwareService.cs
+++ b/optimizerDuck/Services/UI/BloatwareService.cs
@@ -1,4 +1,4 @@
-using System.Collections.Concurrent;
+using System.Collections.Concurrent;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
@@ -93,22 +93,30 @@ public class BloatwareService(
apps.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase));
- foreach (var app in apps)
- {
- if (string.IsNullOrWhiteSpace(app.InstallLocation))
- continue;
+ await Parallel
+ .ForEachAsync(
+ apps,
+ new ParallelOptions
+ {
+ MaxDegreeOfParallelism = Math.Clamp(Environment.ProcessorCount, 2, 8),
+ },
+ (app, _) =>
+ {
+ if (string.IsNullOrWhiteSpace(app.InstallLocation))
+ return ValueTask.CompletedTask;
+
+ try
+ {
+ var manifestLogo = ResolveLogo(app.InstallLocation);
+ if (manifestLogo != null)
+ app.LogoImage = manifestLogo;
+ }
+ catch { }
- try
- {
- var manifestLogo = ResolveLogo(app.InstallLocation);
- if (manifestLogo != null)
- app.LogoImage = manifestLogo;
- }
- catch
- {
- /* Ignore access exceptions */
- }
- }
+ return ValueTask.CompletedTask;
+ }
+ )
+ .ConfigureAwait(false);
#if DEBUG
// Mock AppX package with unusual characters for testing warning dialog in UI
diff --git a/optimizerDuck/Services/UI/DiskCleanupService.cs b/optimizerDuck/Services/UI/DiskCleanupService.cs
index a92a397..7959e55 100644
--- a/optimizerDuck/Services/UI/DiskCleanupService.cs
+++ b/optimizerDuck/Services/UI/DiskCleanupService.cs
@@ -143,7 +143,19 @@ public class DiskCleanupService(ILogger<DiskCleanupService> logger)
/// <param name="items">The items to scan.</param>
public async Task ScanAllAsync(IEnumerable<CleanupItem> items)
{
- await Task.WhenAll(items.Select(ScanAsync));
+ await Parallel
+ .ForEachAsync(
+ items,
+ new ParallelOptions
+ {
+ MaxDegreeOfParallelism = Math.Clamp(Environment.ProcessorCount, 2, 6),
+ },
+ async (item, _) =>
+ {
+ await ScanAsync(item);
+ }
+ )
+ .ConfigureAwait(false);
}
/// <summary>
diff --git a/optimizerDuck/UI/ViewModels/Pages/DashboardViewModel.cs b/optimizerDuck/UI/ViewModels/Pages/DashboardViewModel.cs
index e5f2566..0542cdd 100644
--- a/optimizerDuck/UI/ViewModels/Pages/DashboardViewModel.cs
+++ b/optimizerDuck/UI/ViewModels/Pages/DashboardViewModel.cs
@@ -125,7 +125,16 @@ public partial class DashboardViewModel : ViewModel
if (IsLoading)
return;
- await LoadSystemInfoAsync();
+ if (SystemInfo != null && SystemInfo.Cpu != CpuInfo.Unknown)
+ {
+ RuntimeMemory = _systemInfoService.GetLiveMemory();
+ RuntimeStorage = _systemInfoService.GetLiveStorage();
+ }
+ else
+ {
+ await LoadSystemInfoAsync();
+ }
+
_updateTimer.Start();
}
diff --git a/optimizerDuck/UI/ViewModels/Pages/DiskCleanupViewModel.cs b/optimizerDuck/UI/ViewModels/Pages/DiskCleanupViewModel.cs
index 5cad0ad..65e3f82 100644
--- a/optimizerDuck/UI/ViewModels/Pages/DiskCleanupViewModel.cs
+++ b/optimizerDuck/UI/ViewModels/Pages/DiskCleanupViewModel.cs
@@ -97,11 +97,12 @@ public partial class DiskCleanupViewModel(
{
await base.OnNavigatedToAsync();
- await ScanAsync();
+ if (!IsAllScanned && !IsScanning)
+ {
+ await ScanAsync();
+ }
- CleanupItems = new ObservableCollection<CleanupItem>(
- CleanupItems.OrderByDescending(i => i.SizeBytes).ToArray()
- );
+ ApplySort();
foreach (var item in CleanupItems)
if (item.SizeBytes == 0)