Skip to content

Commit 592c541

Browse files
authored
Optimize package icon loading and memory management (#5069)
1 parent 9d79b42 commit 592c541

10 files changed

Lines changed: 314 additions & 32 deletions

File tree

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
using System;
2+
using System.Runtime.InteropServices;
3+
using System.Threading.Tasks;
4+
using Avalonia.Threading;
5+
using UniGetUI.Core.Logging;
6+
7+
namespace UniGetUI.Avalonia.Infrastructure;
8+
9+
// Collects and returns the working set to the OS once loading has settled — neither .NET nor the
10+
// native allocator hand freed memory back on their own. Debounced so it never runs mid-load.
11+
// Windows-only, best-effort.
12+
internal static class MemoryTrimmer
13+
{
14+
private static readonly TimeSpan SettleDelay = TimeSpan.FromSeconds(3);
15+
private static DispatcherTimer? _timer;
16+
17+
public static void RequestTrimAfterIdle()
18+
{
19+
if (!OperatingSystem.IsWindows()) return;
20+
if (!Dispatcher.UIThread.CheckAccess())
21+
{
22+
Dispatcher.UIThread.Post(RequestTrimAfterIdle);
23+
return;
24+
}
25+
26+
_timer ??= CreateTimer();
27+
_timer.Stop();
28+
_timer.Start();
29+
}
30+
31+
public static void CancelPending()
32+
{
33+
if (!OperatingSystem.IsWindows()) return;
34+
if (!Dispatcher.UIThread.CheckAccess())
35+
{
36+
Dispatcher.UIThread.Post(CancelPending);
37+
return;
38+
}
39+
40+
_timer?.Stop();
41+
}
42+
43+
private static DispatcherTimer CreateTimer()
44+
{
45+
var timer = new DispatcherTimer { Interval = SettleDelay };
46+
timer.Tick += (_, _) =>
47+
{
48+
timer.Stop();
49+
Trim();
50+
};
51+
return timer;
52+
}
53+
54+
private static void Trim() => _ = Task.Run(() =>
55+
{
56+
try
57+
{
58+
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true);
59+
GC.WaitForPendingFinalizers();
60+
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true);
61+
NativeMethods.SetProcessWorkingSetSize(NativeMethods.GetCurrentProcess(), -1, -1);
62+
}
63+
catch (Exception ex)
64+
{
65+
Logger.Warn($"Post-load working-set trim failed: {ex.Message}");
66+
}
67+
});
68+
69+
private static class NativeMethods
70+
{
71+
[DllImport("kernel32.dll")]
72+
public static extern nint GetCurrentProcess();
73+
74+
[DllImport("kernel32.dll", SetLastError = true)]
75+
[return: MarshalAs(UnmanagedType.Bool)]
76+
public static extern bool SetProcessWorkingSetSize(
77+
nint hProcess,
78+
nint dwMinimumWorkingSetSize,
79+
nint dwMaximumWorkingSetSize
80+
);
81+
}
82+
}

‎src/UniGetUI.Avalonia/Models/PackageCollections.cs‎

Lines changed: 118 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
using System.Collections.Concurrent;
21
using System.Collections.ObjectModel;
32
using System.ComponentModel;
43
using System.Net.Http;
4+
using Avalonia;
55
using Avalonia.Collections;
66
using Avalonia.Media.Imaging;
77
using Avalonia.Threading;
@@ -27,8 +27,66 @@ public sealed class PackageWrapper : INotifyPropertyChanged, IDisposable
2727
{
2828
Timeout = TimeSpan.FromSeconds(8),
2929
};
30-
private static readonly ConcurrentDictionary<long, Bitmap?> _iconCache = new();
31-
private static readonly SemaphoreSlim _iconLoadSemaphore = new(4, 4);
30+
private static readonly SemaphoreSlim _iconLoadSemaphore = new(8, 8);
31+
32+
// Cap decoded icon size; the list shows icons at ≤64px (128 covers 2x DPI).
33+
private const int MaxIconSide = 128;
34+
35+
// Bounded LRU by package hash. Evicted entries aren't disposed: a visible row may still
36+
// reference the bitmap, so dropping it here only makes it GC-eligible.
37+
private const int MaxIconCacheEntries = 512;
38+
private static readonly object _iconCacheLock = new();
39+
private static readonly Dictionary<long, LinkedListNode<(long Hash, Bitmap? Bitmap)>> _iconCache = new();
40+
private static readonly LinkedList<(long Hash, Bitmap? Bitmap)> _iconCacheOrder = new();
41+
42+
private static bool TryGetCachedIcon(long hash, out Bitmap? bitmap)
43+
{
44+
lock (_iconCacheLock)
45+
{
46+
if (_iconCache.TryGetValue(hash, out var node))
47+
{
48+
_iconCacheOrder.Remove(node);
49+
_iconCacheOrder.AddFirst(node);
50+
bitmap = node.Value.Bitmap;
51+
return true;
52+
}
53+
}
54+
bitmap = null;
55+
return false;
56+
}
57+
58+
private static void CacheIcon(long hash, Bitmap? bitmap)
59+
{
60+
lock (_iconCacheLock)
61+
{
62+
if (_iconCache.TryGetValue(hash, out var existing))
63+
{
64+
existing.Value = (hash, bitmap);
65+
_iconCacheOrder.Remove(existing);
66+
_iconCacheOrder.AddFirst(existing);
67+
return;
68+
}
69+
70+
var node = new LinkedListNode<(long, Bitmap?)>((hash, bitmap));
71+
_iconCache[hash] = node;
72+
_iconCacheOrder.AddFirst(node);
73+
74+
while (_iconCache.Count > MaxIconCacheEntries && _iconCacheOrder.Last is { } last)
75+
{
76+
_iconCacheOrder.RemoveLast();
77+
_iconCache.Remove(last.Value.Hash);
78+
}
79+
}
80+
}
81+
82+
public static void ClearIconCache()
83+
{
84+
lock (_iconCacheLock)
85+
{
86+
_iconCache.Clear();
87+
_iconCacheOrder.Clear();
88+
}
89+
}
3290

3391
public IPackage Package { get; }
3492
public PackageWrapper Self => this;
@@ -73,6 +131,8 @@ public bool IsChecked
73131
public string InstallerHostChangeTooltip { get; private set; } = "";
74132

75133
private CancellationTokenSource? _installerHostCheckCts;
134+
// Cancels this row's queued/in-flight icon load on disposal so it stops rooting the wrapper.
135+
private readonly CancellationTokenSource _lifetimeCts = new();
76136

77137
public string SourceIconPath => IconTypeToSvgPath(Package.Source.IconId);
78138

@@ -102,12 +162,20 @@ public PackageWrapper(IPackage package, PackagesPageViewModel page)
102162
Package.PropertyChanged += Package_PropertyChanged;
103163
UpdateDisplayState();
104164

105-
if (!Settings.Get(Settings.K.DisableIconsOnPackageLists))
106-
_ = LoadIconAsync();
107-
165+
// Icons load lazily per visible row (see EnsureIconLoaded), not eagerly for every result.
108166
MaybeStartInstallerHostCheck();
109167
}
110168

169+
private int _iconLoadStarted;
170+
171+
/// <summary>Loads this row's icon at most once; called when the row becomes visible.</summary>
172+
public void EnsureIconLoaded()
173+
{
174+
if (Settings.Get(Settings.K.DisableIconsOnPackageLists)) return;
175+
if (Interlocked.Exchange(ref _iconLoadStarted, 1) != 0) return;
176+
_ = LoadIconAsync();
177+
}
178+
111179
/// <summary>
112180
/// For upgradable WinGet packages, asynchronously fetches the installer URL host for
113181
/// both the installed and the new version, and flags the row when the hosts differ.
@@ -183,8 +251,9 @@ await Dispatcher.UIThread.InvokeAsync(() =>
183251

184252
private async Task LoadIconAsync()
185253
{
254+
CancellationToken token = _lifetimeCts.Token;
186255
long hash = Package.GetHash();
187-
if (_iconCache.TryGetValue(hash, out Bitmap? cached))
256+
if (TryGetCachedIcon(hash, out Bitmap? cached))
188257
{
189258
if (cached is not null)
190259
IconBitmap = cached;
@@ -193,12 +262,12 @@ private async Task LoadIconAsync()
193262

194263
try
195264
{
196-
await _iconLoadSemaphore.WaitAsync().ConfigureAwait(false);
265+
await _iconLoadSemaphore.WaitAsync(token).ConfigureAwait(false);
197266
Bitmap bitmap;
198267
try
199268
{
200-
var uri = await Task.Run(Package.GetIconUrlIfAny).ConfigureAwait(false);
201-
if (uri is null) { _iconCache[hash] = null; return; }
269+
var uri = await Task.Run(Package.GetIconUrlIfAny, token).ConfigureAwait(false);
270+
if (uri is null) { CacheIcon(hash, null); return; }
202271

203272
Bitmap? decoded;
204273
if (uri.IsFile)
@@ -207,30 +276,35 @@ private async Task LoadIconAsync()
207276
{
208277
// Avalonia's Bitmap (Skia) can't decode SVG/AVIF/ICO/TIFF — the
209278
// icon cache may produce those. Reject upfront so we don't throw.
210-
_iconCache[hash] = null;
279+
CacheIcon(hash, null);
211280
return;
212281
}
213-
decoded = await Task.Run(() => TryDecodeIcon(uri.LocalPath)).ConfigureAwait(false);
282+
decoded = await Task.Run(() => TryDecodeIcon(uri.LocalPath), token).ConfigureAwait(false);
214283
}
215284
else if (uri.Scheme is "http" or "https")
216285
{
217-
var bytes = await _iconHttpClient.GetByteArrayAsync(uri).ConfigureAwait(false);
286+
var bytes = await _iconHttpClient.GetByteArrayAsync(uri, token).ConfigureAwait(false);
218287
decoded = TryDecodeIcon(bytes, uri.Host);
219288
}
220-
else { _iconCache[hash] = null; return; }
289+
else { CacheIcon(hash, null); return; }
221290

222-
if (decoded is null) { _iconCache[hash] = null; return; }
291+
if (decoded is null) { CacheIcon(hash, null); return; }
223292
bitmap = decoded;
224-
_iconCache[hash] = bitmap;
293+
CacheIcon(hash, bitmap);
225294
}
226295
finally
227296
{
228297
_iconLoadSemaphore.Release();
229298
}
230299

231-
await Dispatcher.UIThread.InvokeAsync(() => IconBitmap = bitmap);
300+
if (token.IsCancellationRequested) return;
301+
await Dispatcher.UIThread.InvokeAsync(() =>
302+
{
303+
if (!token.IsCancellationRequested) IconBitmap = bitmap;
304+
});
232305
}
233-
catch { _iconCache[hash] = null; }
306+
catch (OperationCanceledException) { /* row discarded before its icon finished loading */ }
307+
catch { CacheIcon(hash, null); }
234308
}
235309

236310
// Icons come from a shared on-disk cache that can hold empty or partial entries after an
@@ -239,18 +313,41 @@ private async Task LoadIconAsync()
239313
{
240314
var info = new FileInfo(filePath);
241315
if (!info.Exists || info.Length == 0) return null;
242-
return TryDecodeIcon(() => new Bitmap(filePath), filePath);
316+
return TryDecodeIcon(() => { using var fs = File.OpenRead(filePath); return DecodeDownscaled(fs); }, filePath);
243317
}
244318

245319
private static Bitmap? TryDecodeIcon(byte[] bytes, string source)
246-
=> bytes.Length == 0 ? null : TryDecodeIcon(() => new Bitmap(new MemoryStream(bytes)), source);
320+
=> bytes.Length == 0 ? null : TryDecodeIcon(() => { using var ms = new MemoryStream(bytes); return DecodeDownscaled(ms); }, source);
247321

248322
private static Bitmap? TryDecodeIcon(Func<Bitmap> decode, string source)
249323
{
250324
try { return decode(); }
251325
catch (Exception ex) { Logger.Debug($"Discarding undecodable icon '{source}': {ex.Message}"); return null; }
252326
}
253327

328+
// Downscales oversized icons to MaxIconSide; small icons pass through (never upscaled).
329+
private static Bitmap DecodeDownscaled(Stream stream)
330+
{
331+
var bitmap = new Bitmap(stream);
332+
PixelSize size = bitmap.PixelSize;
333+
if (size.Width <= MaxIconSide && size.Height <= MaxIconSide)
334+
return bitmap;
335+
336+
double scale = (double)MaxIconSide / Math.Max(size.Width, size.Height);
337+
var target = new PixelSize(
338+
Math.Max(1, (int)Math.Round(size.Width * scale)),
339+
Math.Max(1, (int)Math.Round(size.Height * scale)));
340+
341+
try
342+
{
343+
return bitmap.CreateScaledBitmap(target, BitmapInterpolationMode.HighQuality);
344+
}
345+
finally
346+
{
347+
bitmap.Dispose();
348+
}
349+
}
350+
254351
private static bool IsSkiaDecodableExtension(string path)
255352
{
256353
string ext = Path.GetExtension(path);
@@ -314,6 +411,7 @@ public void Dispose()
314411
_installerHostCheckCts?.Cancel();
315412
_installerHostCheckCts?.Dispose();
316413
_installerHostCheckCts = null;
414+
_lifetimeCts.Cancel(); // not disposed: a background load may still hold the token
317415
}
318416
}
319417

‎src/UniGetUI.Avalonia/UniGetUI.Avalonia.csproj‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,11 @@
3434
<PublishReadyToRun>false</PublishReadyToRun>
3535
</PropertyGroup>
3636

37+
<ItemGroup>
38+
<!-- Let the GC decommit unused heap back to the OS; the app is idle most of the time. -->
39+
<RuntimeHostConfigurationOption Include="System.GC.ConserveMemory" Value="5" Trim="false" />
40+
</ItemGroup>
41+
3742
<PropertyGroup Condition="$([MSBuild]::IsOSPlatform('Windows'))">
3843
<!-- Parameterized windows/base views are directly constructed in code, not through the runtime XAML loader. -->
3944
<NoWarn>$(NoWarn);MVVMTK0045;AVLN3001</NoWarn>
@@ -229,6 +234,7 @@
229234
<Compile Include="Infrastructure\AppShortcutAumidStamper.cs" />
230235
<Compile Include="Infrastructure\TrayService.cs" />
231236
<Compile Include="Infrastructure\MicaWindowHelper.cs" />
237+
<Compile Include="Infrastructure\MemoryTrimmer.cs" />
232238
<Compile Include="Infrastructure\EntrancePageTransition.cs" />
233239
<Compile Include="Infrastructure\DirectionalSlideTransition.cs" />
234240
<Compile Include="Infrastructure\MacOsNotificationBridge.cs" />

‎src/UniGetUI.Avalonia/ViewModels/MainWindowViewModel.cs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -367,9 +367,16 @@ public MainWindowViewModel()
367367
if (loader is null) continue;
368368
var pt = pageType;
369369
loader.FinishedLoading += (_, _) =>
370+
{
370371
Dispatcher.UIThread.Post(() => Sidebar.SetNavItemLoading(pt, false));
372+
// Return the load's memory to the OS once it settles.
373+
Infrastructure.MemoryTrimmer.RequestTrimAfterIdle();
374+
};
371375
loader.StartedLoading += (_, _) =>
376+
{
372377
Dispatcher.UIThread.Post(() => Sidebar.SetNavItemLoading(pt, true));
378+
Infrastructure.MemoryTrimmer.CancelPending();
379+
};
373380
Sidebar.SetNavItemLoading(pt, loader.IsLoading);
374381
}
375382

‎src/UniGetUI.Avalonia/ViewModels/Pages/SettingsPages/Interface_PViewModel.cs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ private async Task ResetIconCache(Visual? _)
3434
{
3535
try { Directory.Delete(CoreData.UniGetUICacheDirectory_Icons, true); }
3636
catch (Exception ex) { Logger.Error(ex); }
37+
global::UniGetUI.PackageEngine.PackageClasses.PackageWrapper.ClearIconCache();
3738
RestartRequired?.Invoke(this, EventArgs.Empty);
3839
await LoadIconCacheSize();
3940
}

0 commit comments

Comments
 (0)