Skip to content

Commit 6ef60b4

Browse files
Fix deterministic resource lifetimes (#5070)
1 parent 592c541 commit 6ef60b4

34 files changed

Lines changed: 1409 additions & 405 deletions

File tree

‎src/ExternalLibraries.FilePickers/Classes/Helper.cs‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ internal static class Helper
1717
internal static string ShowOpen(nint windowHandle, FOS fos, List<string>? typeFilters = null)
1818
{
1919
FileOpenDialog dialog = new();
20+
IShellItem item = null!;
2021
try
2122
{
2223
dialog.SetOptions(fos);
@@ -36,13 +37,15 @@ internal static string ShowOpen(nint windowHandle, FOS fos, List<string>? typeFi
3637
return string.Empty;
3738
}
3839

39-
dialog.GetResult(out IShellItem item);
40+
dialog.GetResult(out item);
4041
item.GetDisplayName(SIGDN.SIGDN_FILESYSPATH, out string path);
4142
return path;
4243
}
4344
finally
4445
{
4546
#pragma warning disable CA1416
47+
if (item is not null)
48+
Marshal.ReleaseComObject(item);
4649
Marshal.ReleaseComObject(dialog);
4750
#pragma warning restore CA1416
4851
}
@@ -56,6 +59,7 @@ internal static string ShowSave(
5659
)
5760
{
5861
FileSaveDialog dialog = new();
62+
IShellItem item = null!;
5963
try
6064
{
6165
dialog.SetOptions(fos);
@@ -79,7 +83,7 @@ internal static string ShowSave(
7983
return string.Empty;
8084
}
8185

82-
dialog.GetResult(out IShellItem item);
86+
dialog.GetResult(out item);
8387
item.GetDisplayName(SIGDN.SIGDN_FILESYSPATH, out string path);
8488

8589
dialog.GetFileTypeIndex(out uint selection);
@@ -92,6 +96,8 @@ internal static string ShowSave(
9296
finally
9397
{
9498
#pragma warning disable CA1416
99+
if (item is not null)
100+
Marshal.ReleaseComObject(item);
95101
Marshal.ReleaseComObject(dialog);
96102
#pragma warning restore CA1416
97103
}

‎src/UniGetUI.Avalonia/ViewModels/Controls/UserAvatarViewModel.cs‎

Lines changed: 70 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,13 @@
99

1010
namespace UniGetUI.Avalonia.ViewModels.Controls;
1111

12-
public class UserAvatarViewModel : ViewModelBase
12+
public class UserAvatarViewModel : ViewModelBase, IDisposable
1313
{
14+
private readonly CancellationTokenSource _lifetimeCancellation = new();
15+
private readonly CancellationToken _lifetimeToken;
16+
private int _isDisposed;
17+
private long _refreshGeneration;
18+
1419
private bool _isAuthenticated;
1520
public bool IsAuthenticated
1621
{
@@ -38,15 +43,32 @@ public Bitmap? AvatarBitmap
3843

3944
public UserAvatarViewModel()
4045
{
46+
_lifetimeToken = _lifetimeCancellation.Token;
4147
LoginCommand = new AsyncRelayCommand(LoginAsync);
4248
LogoutCommand = new MvvmRelayCommand(Logout);
4349
MoreDetailsCommand = new MvvmRelayCommand(() => CoreTools.Launch("https://devolutions.net/unigetui"));
44-
GitHubAuthService.AuthStatusChanged += (_, _) => _ = RefreshAsync();
50+
GitHubAuthService.AuthStatusChanged += OnAuthStatusChanged;
4551
_ = RefreshAsync();
4652
}
4753

54+
private bool IsDisposed => Volatile.Read(ref _isDisposed) != 0;
55+
56+
private bool CanApplyRefresh(long generation) =>
57+
!IsDisposed
58+
&& !_lifetimeToken.IsCancellationRequested
59+
&& generation == Volatile.Read(ref _refreshGeneration);
60+
61+
private void OnAuthStatusChanged(object? sender, EventArgs e)
62+
{
63+
if (!IsDisposed)
64+
_ = RefreshAsync();
65+
}
66+
4867
private async Task RefreshAsync()
4968
{
69+
if (IsDisposed) return;
70+
71+
long generation = Interlocked.Increment(ref _refreshGeneration);
5072
var service = new GitHubAuthService();
5173
bool authenticated = GitHubAuthService.IsAuthenticated();
5274

@@ -61,33 +83,56 @@ private async Task RefreshAsync()
6183
if (client is not null)
6284
{
6385
GitHubUser user = await client.GetCurrentUserAsync();
86+
if (!CanApplyRefresh(generation)) return;
87+
6488
displayName = string.IsNullOrEmpty(user.Name)
6589
? $"@{user.Login}"
6690
: $"{user.Name} (@{user.Login})";
6791

6892
if (!string.IsNullOrEmpty(user.AvatarUrl))
6993
{
7094
using var http = new HttpClient(CoreTools.GenericHttpClientParameters);
71-
byte[] bytes = await http.GetByteArrayAsync(user.AvatarUrl);
95+
byte[] bytes = await http.GetByteArrayAsync(user.AvatarUrl, _lifetimeToken);
96+
if (!CanApplyRefresh(generation)) return;
97+
7298
using var ms = new MemoryStream(bytes);
7399
bitmap = new Bitmap(ms);
74100
}
75101
}
76102
}
103+
catch (OperationCanceledException) when (_lifetimeToken.IsCancellationRequested)
104+
{
105+
return;
106+
}
77107
catch (Exception ex)
78108
{
79-
Logger.Warn("UserAvatarViewModel: failed to fetch GitHub user info");
80-
Logger.Warn(ex);
109+
if (!IsDisposed)
110+
{
111+
Logger.Warn("UserAvatarViewModel: failed to fetch GitHub user info");
112+
Logger.Warn(ex);
113+
}
81114
authenticated = false;
82115
}
83116
}
84117

118+
if (!CanApplyRefresh(generation))
119+
{
120+
bitmap?.Dispose();
121+
return;
122+
}
123+
85124
await Dispatcher.UIThread.InvokeAsync(() =>
86125
{
126+
if (!CanApplyRefresh(generation)) return;
127+
87128
IsAuthenticated = authenticated;
88129
UserDisplayName = displayName;
89130
AvatarBitmap = bitmap;
131+
bitmap = null;
90132
});
133+
134+
// A queued UI update can become obsolete while it is waiting to run.
135+
bitmap?.Dispose();
91136
}
92137

93138
private async Task LoginAsync()
@@ -98,8 +143,11 @@ private async Task LoginAsync()
98143
}
99144
catch (Exception ex)
100145
{
101-
Logger.Error("UserAvatarViewModel: login failed");
102-
Logger.Error(ex);
146+
if (!IsDisposed)
147+
{
148+
Logger.Error("UserAvatarViewModel: login failed");
149+
Logger.Error(ex);
150+
}
103151
}
104152
}
105153

@@ -108,8 +156,21 @@ private void Logout()
108156
try { new GitHubAuthService().SignOut(); }
109157
catch (Exception ex)
110158
{
111-
Logger.Error("UserAvatarViewModel: logout failed");
112-
Logger.Error(ex);
159+
if (!IsDisposed)
160+
{
161+
Logger.Error("UserAvatarViewModel: logout failed");
162+
Logger.Error(ex);
163+
}
113164
}
114165
}
166+
167+
public void Dispose()
168+
{
169+
if (Interlocked.Exchange(ref _isDisposed, 1) != 0) return;
170+
171+
GitHubAuthService.AuthStatusChanged -= OnAuthStatusChanged;
172+
// In-flight HTTP work can still observe this token. Cancelling is sufficient;
173+
// disposing the source here could race with that work.
174+
_lifetimeCancellation.Cancel();
175+
}
115176
}

0 commit comments

Comments
 (0)