Skip to content

Commit 462d020

Browse files
committed
fix(imaging): Keep a shared BitmapImage download alive when one requester cancels
The in-flight load cached by URI and decode size is awaited by every BitmapImage opening the same source, but it ran on the first requester's cancellation token. When that requester re-opened (a recycled ListView container binding a new UriSource), the shared task completed with a cancellation error, so every other BitmapImage for that URI raised ImageFailed and stayed blank, and nothing retried. The shared load now runs on no requester's token, as WinUI's ImageCache does when a request is released, and each requester waits under its own token so a cancelled open neither fails nor applies a stale result. Uncached loads (IgnoreImageCache or cache disabled) still cancel with their sole requester. A cached load that completes with an error also stayed in the LRU until eviction, so one transient failure (offline moment, 503, DNS hiccup) kept failing every later BitmapImage for that URI with no retry. A continuation on the shared task now removes the entry when the load fails, guarded by the new identity-checked LRUCache.Remove(key, value) so it only removes the entry while it still holds that very task, and a lookup that sees a failed load before the continuation ran treats it as a miss. Fixes unoplatform#25096
1 parent 91ec143 commit 462d020

3 files changed

Lines changed: 287 additions & 13 deletions

File tree

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

Lines changed: 220 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,17 @@
22
#nullable enable
33

44
using System;
5+
using System.IO;
6+
using System.Net;
7+
using System.Net.Sockets;
8+
using System.Text;
9+
using System.Threading;
510
using System.Threading.Tasks;
611
using Microsoft.UI.Xaml.Controls;
712
using Microsoft.UI.Xaml.Media.Imaging;
13+
using Private.Infrastructure;
814
using Uno.UI.RuntimeTests.Helpers;
15+
using Windows.Storage;
916
using static Private.Infrastructure.TestServices;
1017

1118
namespace Uno.UI.RuntimeTests.Tests.Windows_UI_Xaml_Media_Imaging;
@@ -64,5 +71,218 @@ private static async Task LoadAsync(Panel panel, Uri uri, int decodePixelWidth,
6471

6572
await tcs.Task.WaitAsync(TimeSpan.FromSeconds(10));
6673
}
74+
75+
[TestMethod]
76+
[PlatformCondition(ConditionMode.Include, RuntimeTestPlatforms.SkiaDesktop)]
77+
[GitHubWorkItem("https://github.com/unoplatform/uno/issues/25096")]
78+
public async Task When_Shared_Download_And_First_Requester_Cancelled()
79+
{
80+
using var server = await GatedImageServer.StartAsync();
81+
82+
var first = new BitmapImage(server.Uri);
83+
var second = new BitmapImage(server.Uri);
84+
var firstResult = TrackOpen(first);
85+
var secondResult = TrackOpen(second);
86+
87+
// Subscribing an Image is what opens the source; both join the same cached download.
88+
var firstImage = new Image { Source = first };
89+
var secondImage = new Image { Source = second };
90+
91+
await WindowHelper.WaitFor(() => server.RequestCount >= 1, 5000, "the download never started");
92+
93+
// Cancels the first requester while the shared download is in flight (what a recycled container does).
94+
first.UriSource = null;
95+
96+
server.ReleaseResponses();
97+
98+
Assert.IsTrue(await secondResult.WaitAsync(TimeSpan.FromSeconds(10)), "The second BitmapImage should open");
99+
Assert.AreEqual(100, second.PixelWidth);
100+
Assert.AreEqual(1, server.RequestCount, "Both sources should share one download");
101+
Assert.IsFalse(firstResult.IsCompleted, "The cancelled BitmapImage should raise neither ImageOpened nor ImageFailed");
102+
103+
GC.KeepAlive(firstImage);
104+
GC.KeepAlive(secondImage);
105+
}
106+
107+
[TestMethod]
108+
[PlatformCondition(ConditionMode.Include, RuntimeTestPlatforms.SkiaDesktop)]
109+
[GitHubWorkItem("https://github.com/unoplatform/uno/issues/25096")]
110+
public async Task When_Only_Requester_Cancelled_Then_Same_Uri_Reopened()
111+
{
112+
using var server = await GatedImageServer.StartAsync();
113+
114+
var first = new BitmapImage(server.Uri);
115+
var firstImage = new Image { Source = first };
116+
117+
await WindowHelper.WaitFor(() => server.RequestCount >= 1, 5000, "the download never started");
118+
119+
first.UriSource = null;
120+
server.ReleaseResponses();
121+
122+
var second = new BitmapImage(server.Uri);
123+
var secondResult = TrackOpen(second);
124+
var secondImage = new Image { Source = second };
125+
126+
Assert.IsTrue(await secondResult.WaitAsync(TimeSpan.FromSeconds(10)), "A later BitmapImage for the same Uri should open");
127+
Assert.AreEqual(100, second.PixelWidth);
128+
129+
GC.KeepAlive(firstImage);
130+
GC.KeepAlive(secondImage);
131+
}
132+
133+
[TestMethod]
134+
[PlatformCondition(ConditionMode.Include, RuntimeTestPlatforms.SkiaDesktop)]
135+
[GitHubWorkItem("https://github.com/unoplatform/uno/issues/25096")]
136+
public async Task When_Shared_Download_Failed_Then_Same_Uri_Reopened()
137+
{
138+
using var server = await GatedImageServer.StartAsync();
139+
server.FailNextRequest = true;
140+
server.ReleaseResponses();
141+
142+
var first = new BitmapImage(server.Uri);
143+
var firstResult = TrackOpen(first);
144+
var firstImage = new Image { Source = first };
145+
146+
Assert.IsFalse(await firstResult.WaitAsync(TimeSpan.FromSeconds(10)), "The first BitmapImage should fail");
147+
148+
// The entry is dropped by a continuation on the load, so poll rather than assume it ran before ImageFailed.
149+
await TestHelper.RetryAssert(
150+
async () => Assert.IsNull(await BitmapImage.GetCachedImageDataTaskForTesting(server.Uri, null, null), "The failed load should have been dropped from the cache"),
151+
count: 200);
152+
153+
var second = new BitmapImage(server.Uri);
154+
var secondResult = TrackOpen(second);
155+
var secondImage = new Image { Source = second };
156+
157+
Assert.IsTrue(await secondResult.WaitAsync(TimeSpan.FromSeconds(10)), "A failed download must not be cached: the next BitmapImage should download again and open");
158+
Assert.AreEqual(100, second.PixelWidth);
159+
Assert.AreEqual(2, server.RequestCount, "The second BitmapImage should have downloaded again");
160+
161+
GC.KeepAlive(firstImage);
162+
GC.KeepAlive(secondImage);
163+
}
164+
165+
private static Task<bool> TrackOpen(BitmapImage image)
166+
{
167+
var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
168+
image.ImageOpened += (_, _) => tcs.TrySetResult(true);
169+
image.ImageFailed += (_, _) => tcs.TrySetResult(false);
170+
return tcs.Task;
171+
}
172+
173+
/// <summary>
174+
/// Minimal loopback HTTP server that sends the response headers immediately but holds the image bytes
175+
/// until <see cref="ReleaseResponses"/>, so a test can act while a download is deterministically in flight.
176+
/// With <see cref="FailNextRequest"/> set, the next request gets an HTTP 500 instead of the image.
177+
/// </summary>
178+
private sealed class GatedImageServer : IDisposable
179+
{
180+
private readonly TcpListener _listener;
181+
private readonly byte[] _body;
182+
private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously);
183+
private int _requestCount;
184+
185+
private GatedImageServer(TcpListener listener, byte[] body)
186+
{
187+
_listener = listener;
188+
_body = body;
189+
Uri = new Uri($"http://127.0.0.1:{((IPEndPoint)listener.LocalEndpoint).Port}/square100.png");
190+
_ = AcceptLoopAsync();
191+
}
192+
193+
public static async Task<GatedImageServer> StartAsync()
194+
{
195+
var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/square100.png"));
196+
using var stream = await file.OpenStreamForReadAsync();
197+
using var memory = new MemoryStream();
198+
await stream.CopyToAsync(memory);
199+
200+
var listener = new TcpListener(IPAddress.Loopback, 0);
201+
listener.Start();
202+
return new GatedImageServer(listener, memory.ToArray());
203+
}
204+
205+
public Uri Uri { get; }
206+
207+
public int RequestCount => Volatile.Read(ref _requestCount);
208+
209+
public bool FailNextRequest { get; set; }
210+
211+
public void ReleaseResponses() => _release.TrySetResult();
212+
213+
public void Dispose()
214+
{
215+
_release.TrySetResult();
216+
_listener.Stop();
217+
}
218+
219+
private async Task AcceptLoopAsync()
220+
{
221+
try
222+
{
223+
while (true)
224+
{
225+
var client = await _listener.AcceptTcpClientAsync();
226+
_ = HandleAsync(client);
227+
}
228+
}
229+
catch (ObjectDisposedException)
230+
{
231+
}
232+
catch (SocketException)
233+
{
234+
}
235+
}
236+
237+
private async Task HandleAsync(TcpClient client)
238+
{
239+
try
240+
{
241+
using var _ = client;
242+
using var stream = client.GetStream();
243+
244+
var request = new byte[8192];
245+
var read = 0;
246+
while (!Encoding.ASCII.GetString(request, 0, read).Contains("\r\n\r\n"))
247+
{
248+
var count = await stream.ReadAsync(request, read, request.Length - read);
249+
if (count == 0)
250+
{
251+
return;
252+
}
253+
254+
read += count;
255+
}
256+
257+
Interlocked.Increment(ref _requestCount);
258+
259+
if (FailNextRequest)
260+
{
261+
FailNextRequest = false;
262+
await stream.WriteAsync(Encoding.ASCII.GetBytes("HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"));
263+
await stream.FlushAsync();
264+
return;
265+
}
266+
267+
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();
270+
271+
await _release.Task;
272+
273+
await stream.WriteAsync(_body);
274+
await stream.FlushAsync();
275+
}
276+
catch (IOException)
277+
{
278+
}
279+
catch (ObjectDisposedException)
280+
{
281+
}
282+
catch (SocketException)
283+
{
284+
}
285+
}
286+
}
67287
}
68288
#endif

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

Lines changed: 51 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,9 @@ internal static async Task<Task<ImageData>> GetCachedImageDataTaskForTesting(Uri
2828
// TODO: Introduce LRU caching if needed
2929
private static readonly Dictionary<string, string> _scaledBitmapPathCache = new();
3030

31+
private static bool IsFailedLoad(Task<ImageData> load)
32+
=> load.IsFaulted || (load.IsCompletedSuccessfully && load.Result.Kind == ImageDataKind.Error);
33+
3134
private protected override bool TryOpenSourceAsync(CancellationToken ct, int? targetWidth, int? targetHeight, out Task<ImageData> asyncImage)
3235
{
3336
asyncImage = TryOpenSourceAsync(ct);
@@ -131,37 +134,67 @@ private async Task<ImageData> TryOpenSourceAsync(CancellationToken ct)
131134
uri = await TryResolveLocalResource(uri);
132135
}
133136

134-
var ignoreCache = CreateOptions.HasFlag(BitmapCreateOptions.IgnoreImageCache);
137+
var useCache = FeatureConfiguration.Image.EnableBitmapImageCache
138+
&& !CreateOptions.HasFlag(BitmapCreateOptions.IgnoreImageCache);
135139
var cacheKey = new BitmapImageCacheKey(uri, decodeWidth, decodeHeight);
136140

137-
if (ignoreCache
138-
|| !_bitmapImageCache.TryGetValue(cacheKey, out var imageDataTask))
141+
Task<ImageData> imageDataTask = null;
142+
143+
if (useCache && _bitmapImageCache.TryGetValue(cacheKey, out imageDataTask) && IsFailedLoad(imageDataTask))
139144
{
145+
// A lookup can see a load that just failed before its eviction continuation below has run
146+
// (e.g. an immediate retry from ImageFailed); treat it as a miss so the retry downloads again.
147+
_bitmapImageCache.Remove(cacheKey, imageDataTask);
148+
imageDataTask = null;
149+
}
150+
151+
if (imageDataTask is null)
152+
{
153+
// A cached load is shared by every BitmapImage opening the same key, so it never runs on a single
154+
// requester's token (cancelling one must not fail the others); releasing a request leaves the shared
155+
// download running (MUX Reference: ImageCache::OnRequestReleasing — ImageCache.cpp). Only an
156+
// uncached load is cancelled with its sole requester.
157+
var loadCt = useCache ? CancellationToken.None : ct;
158+
140159
imageDataTask = Task.Run(async () =>
141160
{
142161
try
143162
{
144-
return await ImageSourceHelpers.GetImageDataFromUriAsCompositionSurface(uri, ct, decodeWidth, decodeHeight);
163+
return await ImageSourceHelpers.GetImageDataFromUriAsCompositionSurface(uri, loadCt, decodeWidth, decodeHeight);
145164
}
146165
catch (Exception e)
147166
{
148167
return ImageData.FromError(e);
149168
}
150-
}, ct);
169+
}, loadCt);
151170

152-
// IgnoreImageCache must also skip the add: otherwise the decoded image is
153-
// retained by the cache exactly as if the option were not set.
154-
if (!ignoreCache && FeatureConfiguration.Image.EnableBitmapImageCache)
171+
if (useCache)
155172
{
156173
_bitmapImageCache.Add(cacheKey, imageDataTask);
157-
// if loading failed not because of an actual failure but because
158-
// the task was canceled (usually because the Uri changed), we
159-
// don't want to cache the failed task
160-
ct.Register(() => _bitmapImageCache.Remove(cacheKey));
174+
175+
// A failed load must not keep failing later requesters. WinUI's provider store does not own its
176+
// ImageCache, so a failed one is dropped once released and the next request downloads again
177+
// (MUX Reference: ImageProvider::OnImageCacheInvalidated — ImageProvider.cpp); the LRU owns its
178+
// entries, so drop a failed load as soon as it completes, and only while it is still the stored
179+
// one (MUX Reference: ImageProvider::RemoveImageCache — ImageProvider.cpp).
180+
_ = imageDataTask.ContinueWith(
181+
t =>
182+
{
183+
if (IsFailedLoad(t))
184+
{
185+
_bitmapImageCache.Remove(cacheKey, t);
186+
}
187+
},
188+
CancellationToken.None,
189+
TaskContinuationOptions.ExecuteSynchronously,
190+
TaskScheduler.Default);
161191
}
162192
}
163193

164-
var imageData = await imageDataTask;
194+
var imageData = await imageDataTask.WaitAsync(ct);
195+
196+
// The shared load may have completed between the cancellation and the await.
197+
ct.ThrowIfCancellationRequested();
165198

166199
if (imageData.Kind == ImageDataKind.Error)
167200
{
@@ -180,6 +213,11 @@ private async Task<ImageData> TryOpenSourceAsync(CancellationToken ct)
180213
return imageData;
181214
}
182215
}
216+
catch (OperationCanceledException) when (ct.IsCancellationRequested)
217+
{
218+
// A superseded open is not a load failure; ImageSource.Open drops it.
219+
throw;
220+
}
183221
catch (Exception e)
184222
{
185223
return ImageData.FromError(e);

‎src/Uno.UWP/Helpers/LRUCache.cs‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,22 @@ public void Remove(TKey key)
126126
}
127127
}
128128

129+
/// <summary>
130+
/// Removes the entry for <paramref name="key"/> only if it still holds <paramref name="value"/>,
131+
/// so a stale removal cannot drop a newer entry that replaced it.
132+
/// </summary>
133+
public void Remove(TKey key, TValue value)
134+
{
135+
lock (_gate)
136+
{
137+
if (_table.TryGetValue(key, out var node) && ReferenceEquals(node.Value.val, value))
138+
{
139+
_table.Remove(key);
140+
_queue.Remove(node);
141+
}
142+
}
143+
}
144+
129145
public TValue this[TKey key]
130146
{
131147
set => Add(key, value);

0 commit comments

Comments
 (0)