dotnet / dotnet/maui

TaskCanceledException on IStreamImageSource.GetStreamAsync(CancellationToken userToken)

Open
#28,684 1 comment 1 reaction 0 assignees View on GitHub
area-image
Dominant language
C#
Stars
23.3k
Forks
2k
Avg merge
1d 15h
Merged PRs (30d)
290

Description

My app has an BackgroundImageSource loaded on ctor with the code bellow

```
var imageBytes = System.IO.File.ReadAllBytes(filePath);
if (imageBytes == null)
return;

this.BackgroundImageSource = ImageSource.FromStream(() => new MemoryStream(imageBytes));
```

The method FireAndForget is responsible for applying the image to the UI.

Uncoordinated image loading and UI lifecycle events, compounded by inadequate `TaskCanceledException` handling in `FireAndForget`.

![Image](https://github.com/user-attachments/assets/42b6f3d2-0ac9-4fd8-8bfc-6ec79beb4daf)

```
/_/src/Controls/src/Core/StreamImageSource.cs in async Task StreamImageSource.Microsoft.Maui.IStreamImageSource.GetStreamAsync(CancellationToken userToken) at line 43:5

/_/src/Controls/src/Core/StreamImageSource.cs in async Task StreamImageSource.Microsoft.Maui.IStreamImageSource.GetStreamAsync(CancellationToken userToken) at line 49:5

/_/src/Core/src/ImageSources/StreamImageSourceService/StreamImageSourceService.Android.cs in async Task> StreamImageSourceService.GetDrawableAsync(IImageSource imageSource, Context context, CancellationToken cancellationToken) at line 76:6

/_/src/Core/src/Platform/Android/ViewExtensions.cs in async Task ViewExtensions.UpdateBackgroundImageSourceAsync(View platformView, IImageSource imageSource, IImageSourceServiceProvider provider) at line 422:5

/_/src/Core/src/TaskExtensions.cs in async void TaskExtensions.FireAndForget(Task task, Action errorCallback) at line 36:5
```

When the application navigates to a new page, triggering the `Appearing` lifecycle event, which initiates the image loading process.

This is where the image loading is triggered, setting the stage for the race condition

I've created an PR to fix this
https://github.com/dotnet/maui/pull/28685

Contributor guide

Open the contributing guide

Research direction

Start with src/Controls/src/Core/StreamImageSource.cs and follow the reported stack through StreamImageSourceService.Android.cs, ViewExtensions.cs, and TaskExtensions.cs. Review the proposed fix in PR #28685, then run the reported navigation and image-loading scenario; done means the cancellation no longer produces the reported unhandled exception.

Written by the indexing model from the issue text.

Assessment

Tech stack
android, csharp
Domain
mobile-dev
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.