Skip to content

Commit f443e7c

Browse files
committed
fix(imaging): Release the decode of a cancelled requester
A source whose open was superseded while its download or decode was in flight produced a surface that nothing displayed: ImageSource.Open dropped a result that arrived after cancellation, and a BitmapImage requester that was cancelled out of waiting on its own load never saw what the load produced. Each such surface waited for finalization, so clicking quickly through large images piled them up. A result that arrives after cancellation is now released at once, and a cancelled requester attaches a continuation to its uncached load that releases the surface it produces. Cached loads are shared and stay the cache's. unoplatform#25114
1 parent cd1a619 commit f443e7c

5 files changed

Lines changed: 116 additions & 15 deletions

File tree

‎src/Uno.UI.RuntimeTests/Tests/Windows_UI_Xaml_Media_Imaging/Given_BitmapImage.cs‎

Lines changed: 57 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
using System.Threading;
1010
using System.Threading.Tasks;
1111
using Microsoft.UI.Xaml.Controls;
12+
using Microsoft.UI.Xaml.Media;
13+
using Uno.UI.Xaml.Media;
1214
using Microsoft.UI.Xaml.Media.Imaging;
1315
using Private.Infrastructure;
1416
using Uno.UI.RuntimeTests.Helpers;
@@ -162,6 +164,47 @@ await TestHelper.RetryAssert(
162164
GC.KeepAlive(secondImage);
163165
}
164166

167+
[TestMethod]
168+
[PlatformCondition(ConditionMode.Include, RuntimeTestPlatforms.SkiaDesktop)]
169+
[GitHubWorkItem("https://github.com/unoplatform/uno/issues/25114")]
170+
public async Task When_Requester_Cancelled_After_Decode_Then_Abandoned_Surface_Released()
171+
{
172+
// Without the cache the load belongs to this source alone. The decode runs off the UI thread and its result is applied
173+
// by a dispatched continuation; a source change that lands first (a user clicking through images quickly) must release
174+
// the surface that continuation would otherwise drop.
175+
var cacheWasEnabled = FeatureConfiguration.Image.EnableBitmapImageCache;
176+
FeatureConfiguration.Image.EnableBitmapImageCache = false;
177+
178+
try
179+
{
180+
using var server = await GatedImageServer.StartAsync();
181+
var bitmap = new BitmapImage(server.Uri);
182+
var result = TrackOpen(bitmap);
183+
var image = new Image { Source = bitmap };
184+
185+
await WindowHelper.WaitFor(() => server.RequestCount >= 1, 5000, "the download never started");
186+
187+
var createdBefore = ImageData.CompositionSurfacesCreatedForTesting;
188+
var releasedBefore = ImageSource.ReleasedSurfacesForTesting;
189+
server.ReleaseResponses();
190+
191+
// Holding the UI thread keeps the dispatched continuation from applying the result while the decode completes.
192+
var decoded = SpinWait.SpinUntil(() => ImageData.CompositionSurfacesCreatedForTesting > createdBefore, 5000);
193+
Assert.IsTrue(decoded, $"Pre-condition: the decode must complete (requests {server.RequestCount}, bodies sent {server.BodiesSent}, surfaces {ImageData.CompositionSurfacesCreatedForTesting - createdBefore}, opened {result.IsCompleted})");
194+
195+
bitmap.UriSource = null;
196+
await WindowHelper.WaitForIdle();
197+
198+
Assert.IsTrue(ImageSource.ReleasedSurfacesForTesting > releasedBefore, "The decoded surface nobody will show must be released");
199+
Assert.IsFalse(result.IsCompleted, "The cancelled BitmapImage should raise neither ImageOpened nor ImageFailed");
200+
GC.KeepAlive(image);
201+
}
202+
finally
203+
{
204+
FeatureConfiguration.Image.EnableBitmapImageCache = cacheWasEnabled;
205+
}
206+
}
207+
165208
private static Task<bool> TrackOpen(BitmapImage image)
166209
{
167210
var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
@@ -181,13 +224,16 @@ private sealed class GatedImageServer : IDisposable
181224
private readonly byte[] _body;
182225
private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously);
183226
private int _requestCount;
227+
private int _bodiesSent;
184228

185229
private GatedImageServer(TcpListener listener, byte[] body)
186230
{
187231
_listener = listener;
188232
_body = body;
189233
Uri = new Uri($"http://127.0.0.1:{((IPEndPoint)listener.LocalEndpoint).Port}/square100.png");
190-
_ = AcceptLoopAsync();
234+
// Off the UI thread: the test may hold the UI thread while a response is pending, and awaits started from it
235+
// would otherwise resume through its synchronization context.
236+
_ = Task.Run(AcceptLoopAsync);
191237
}
192238

193239
public static async Task<GatedImageServer> StartAsync()
@@ -206,6 +252,8 @@ public static async Task<GatedImageServer> StartAsync()
206252

207253
public int RequestCount => Volatile.Read(ref _requestCount);
208254

255+
public int BodiesSent => Volatile.Read(ref _bodiesSent);
256+
209257
public bool FailNextRequest { get; set; }
210258

211259
public void ReleaseResponses() => _release.TrySetResult();
@@ -222,7 +270,7 @@ private async Task AcceptLoopAsync()
222270
{
223271
while (true)
224272
{
225-
var client = await _listener.AcceptTcpClientAsync();
273+
var client = await _listener.AcceptTcpClientAsync().ConfigureAwait(false);
226274
_ = HandleAsync(client);
227275
}
228276
}
@@ -245,7 +293,7 @@ private async Task HandleAsync(TcpClient client)
245293
var read = 0;
246294
while (!Encoding.ASCII.GetString(request, 0, read).Contains("\r\n\r\n"))
247295
{
248-
var count = await stream.ReadAsync(request, read, request.Length - read);
296+
var count = await stream.ReadAsync(request, read, request.Length - read).ConfigureAwait(false);
249297
if (count == 0)
250298
{
251299
return;
@@ -265,13 +313,14 @@ private async Task HandleAsync(TcpClient client)
265313
}
266314

267315
var headers = $"HTTP/1.1 200 OK\r\nContent-Type: image/png\r\nContent-Length: {_body.Length}\r\nConnection: close\r\n\r\n";
268-
await stream.WriteAsync(Encoding.ASCII.GetBytes(headers));
269-
await stream.FlushAsync();
316+
await stream.WriteAsync(Encoding.ASCII.GetBytes(headers)).ConfigureAwait(false);
317+
await stream.FlushAsync().ConfigureAwait(false);
270318

271-
await _release.Task;
319+
await _release.Task.ConfigureAwait(false);
272320

273-
await stream.WriteAsync(_body);
274-
await stream.FlushAsync();
321+
await stream.WriteAsync(_body).ConfigureAwait(false);
322+
await stream.FlushAsync().ConfigureAwait(false);
323+
Interlocked.Increment(ref _bodiesSent);
275324
}
276325
catch (IOException)
277326
{

‎src/Uno.UI/UI/Xaml/Media/ImageData.cs‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,16 @@ private ImageData(_UIImage uiImage)
4242
NativeImage = uiImage ?? throw new ArgumentNullException(nameof(uiImage));
4343
}
4444
#elif __SKIA__
45-
public static ImageData FromCompositionSurface(SkiaCompositionSurface compositionSurface) => new(compositionSurface);
45+
/// <summary>
46+
/// Number of decoded surfaces produced; for tests.
47+
/// </summary>
48+
internal static int CompositionSurfacesCreatedForTesting;
49+
50+
public static ImageData FromCompositionSurface(SkiaCompositionSurface compositionSurface)
51+
{
52+
CompositionSurfacesCreatedForTesting++;
53+
return new(compositionSurface);
54+
}
4655

4756
private ImageData(SkiaCompositionSurface compositionSurface)
4857
{

‎src/Uno.UI/UI/Xaml/Media/ImageSource.crossruntime.cs‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,8 @@ private void ReleaseImageData()
106106

107107
partial void ReleaseImageDataPlatform();
108108

109+
partial void ReleaseAbandonedImageData(ImageData data);
110+
109111
/// <summary>
110112
/// Indicates that this source has already been opened
111113
/// (So the onSourceOpened callback of Subscribe will be invoked synchronously!)
@@ -143,6 +145,12 @@ private void Open()
143145
{
144146
OnOpened(data);
145147
}
148+
else
149+
{
150+
// A superseded open still produced an image nobody will show: release it now rather than leave it
151+
// to finalization, which is what a burst of source changes would otherwise pile up.
152+
ReleaseAbandonedImageData(data);
153+
}
146154
}
147155
catch (OperationCanceledException) when (ct.IsCancellationRequested)
148156
{

‎src/Uno.UI/UI/Xaml/Media/ImageSource.skia.cs‎

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,30 @@ namespace Microsoft.UI.Xaml.Media;
66

77
partial class ImageSource
88
{
9-
partial void ReleaseImageDataPlatform()
9+
/// <summary>
10+
/// Number of decoded surfaces released ahead of finalization; for tests.
11+
/// </summary>
12+
internal static int ReleasedSurfacesForTesting;
13+
14+
partial void ReleaseImageDataPlatform() => ReleaseSurface(_imageData);
15+
16+
partial void ReleaseAbandonedImageData(ImageData data)
17+
{
18+
if (!SharesImageData)
19+
{
20+
ReleaseSurface(data);
21+
}
22+
}
23+
24+
/// <summary>
25+
/// Releases the decoded frames of an image surface that nothing will display.
26+
/// </summary>
27+
internal static void ReleaseSurface(ImageData data)
1028
{
11-
if (_imageData.Kind == ImageDataKind.CompositionSurface)
29+
if (data.Kind == ImageDataKind.CompositionSurface && data.CompositionSurface is { } surface)
1230
{
13-
_imageData.CompositionSurface?.ReleaseFrames();
31+
surface.ReleaseFrames();
32+
ReleasedSurfacesForTesting++;
1433
}
1534
}
1635
}

‎src/Uno.UI/UI/Xaml/Media/Imaging/BitmapImage.skia.cs‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -196,10 +196,26 @@ private async Task<ImageData> TryOpenSourceAsync(CancellationToken ct)
196196
}
197197
}
198198

199-
var imageData = await imageDataTask.WaitAsync(ct);
199+
ImageData imageData;
200200

201-
// The shared load may have completed between the cancellation and the await.
202-
ct.ThrowIfCancellationRequested();
201+
try
202+
{
203+
imageData = await imageDataTask.WaitAsync(ct);
204+
205+
// The shared load may have completed between the cancellation and the await.
206+
ct.ThrowIfCancellationRequested();
207+
}
208+
catch (OperationCanceledException) when (ct.IsCancellationRequested && !useCache)
209+
{
210+
// The decode cannot be stopped and this requester will never show its result, so release the surface
211+
// it produces instead of leaving it to finalization. A cached load is shared and stays the cache's.
212+
_ = imageDataTask.ContinueWith(
213+
static t => ReleaseSurface(t.Result),
214+
CancellationToken.None,
215+
TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously,
216+
TaskScheduler.Default);
217+
throw;
218+
}
203219

204220
if (imageData.Kind == ImageDataKind.Error)
205221
{

0 commit comments

Comments
 (0)