Skip to content

[iOS] Fix MediaPicker UIKit threading when picking multiple items - #38465

Closed
kubaflo wants to merge 1 commit into
mainfrom
kubaflo-forward-port-mediapicker-fix
Closed

kubaflo wants to merge 1 commit into
mainfrom
kubaflo-forward-port-mediapicker-fix

Conversation

@kubaflo

@kubaflo kubaflo commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

Note

Are you waiting for the changes in this PR to be merged?
It would be very helpful if you could test the resulting artifacts from this PR and let us know in a comment if this change resolves your issue. Thank you!

Description of Change

Forward-ports the merged fix from #37879 (inflight/current) to main for #37878.

PickerResultsToMediaFiles previously read each PHPickerResult.ItemProvider after an awaited operation resumed on a thread-pool thread. Picking two or more items could therefore throw UIKitThreadAccessException. The fix materializes all item providers on the UI thread before the first await, then loads their file representations separately. It also disposes providers that remain unloaded if loading fails.

SR11 Backport Sequence

This main forward-port must merge before the SR11 backport is created. After this PR merges, its merge commit can be backported to release/10.0.1xx-sr11. No SR11 PR, release-ref push, or /backport request has been created yet.

Provenance

Cherry-picked the single-parent squash merge commit 11ed1aeb65f7fd2fbfb0fed5de967380d7fa54a4 from #37879 with explicit provenance. The patch applied without conflicts and has the same stable patch ID as the source (2097bc330feea531a113c4d3eb3a56cb0263f67a). Patch version 120 remains unchanged.

Validation

  • dotnet format src/Essentials/src/Essentials.csproj --no-restore --include src/Essentials/src/MediaPicker/MediaPicker.ios.cs --verify-no-changes
  • dotnet build src/Essentials/src/Essentials.csproj -f net10.0-ios26.0 --no-restore /p:BuildIpa=false /p:EnableSourceLink=false /p:UseSharedCompilation=false
  • dotnet build src/Essentials/src/Essentials.csproj -f net10.0-maccatalyst26.0 --no-restore /p:EnableSourceLink=false /p:UseSharedCompilation=false

Both builds completed with 0 warnings and 0 errors. The original runtime verification remains documented in #37879.

Issues Addressed

#37878

…g 2+ items (#37879)

### Description of Change

`PickerResultsToMediaFiles` reads `PHPickerResult.ItemProvider` — a
UIKit call guarded by `UIApplication.EnsureUIThread()` — inside a loop
that awaits with `ConfigureAwait(false)`:

```csharp
foreach (var file in results)
{
    fileResult = new PHPickerFileResult(file.ItemProvider);   // UIKit call
    await fileResult.LoadFileRepresentationAsync().ConfigureAwait(false);
    fileResults.Add(fileResult);
    fileResult = null;
}
```

The first iteration runs on the main thread, because the picker delegate
invokes it from the dismissal completion. But
`LoadFileRepresentationAsync` completes through a
`TaskCompletionSource<bool>` created with
`TaskCreationOptions.RunContinuationsAsynchronously`, so the
continuation never runs inline. From the second iteration onwards the
read happens on the thread pool and throws `UIKitThreadAccessException`.
This makes it deterministic rather than a race — picking 2 or more items
always fails, picking 1 always works.

This is a regression from #35805, which replaced the previous
`Select(...).ToList()` materialization — where every `ItemProvider` was
read before the first await — with the loop above.

**Change:** read every `ItemProvider` up front, before the first await,
then load the file representations in a second loop. `NSItemProvider` is
a Foundation type with no UI-thread guard, so holding the providers
across the awaits is safe.

This preserves what #35805 set out to fix: `FullPath` is assigned in the
`PHPickerFileResult` constructor via `CreateTemporaryFilePath`, not by
the load, so it still points at a real temp-backed file. Ordering, image
processing and video handling are untouched.

It also fixes a leak in the error path: previously, when a load threw,
results already constructed by earlier iterations were disposed, but
ones constructed later were not. Results are now only added to the
returned list once loaded, and any left unloaded by a failure are
disposed separately.

### Verification

- `dotnet format src/Essentials/src/Essentials.csproj --no-restore
--include src/Essentials/src/MediaPicker/MediaPicker.ios.cs
--verify-no-changes` — clean
- `dotnet build src/Essentials/src/Essentials.csproj -f net10.0-ios26.0
--no-restore /p:BuildIpa=false /p:EnableSourceLink=false
/p:UseSharedCompilation=false` — 0 warnings, 0 errors
- `dotnet build src/Essentials/src/Essentials.csproj -f
net10.0-maccatalyst26.0 --no-restore /p:EnableSourceLink=false
/p:UseSharedCompilation=false` — 0 warnings, 0 errors
- Ran on the iOS 26.4 simulator (iPhone 17) by dropping the built
`Microsoft.Maui.Essentials.dll` into the repro app from the issue, so
the real fixed code was exercised through
`MediaPicker.Default.PickPhotosAsync`:
  - picking 3 photos no longer throws
- every returned `FileResult.FullPath` exists, is non-empty, and
`File.Copy(result.FullPath, ...)` succeeds — i.e. the #32832 scenario
that #35805 fixed still works

No unit test is included: the affected path needs a real
`PHPickerResult`, which cannot be constructed in `Essentials.UnitTests`.
Happy to add coverage if you can point me at a suitable seam.

### Issues Fixed

Fixes #37878

(cherry picked from commit 11ed1ae)

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI lite review requested due to automatic review settings September 11, 2026 22:40
@github-actions

Copy link
Copy Markdown
Contributor

🚀 Dogfood this PR with:

⚠️ WARNING: Do not do this without first carefully reviewing the code of this PR to satisfy yourself it is safe.

curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 38465

Or

  • Run remotely in PowerShell:
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 38465"

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).
There may be pipelines that require an authorized user to comment /azp run to run.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

UIKit threading changes warrant final human verification.

Pull request overview

Fixes iOS MediaPicker UIKit threading failures during multi-item selection and improves cleanup when loading fails.

Changes:

  • Materializes item providers on the UI thread before asynchronous loading.
  • Improves disposal of loaded and unloaded results on failure.
File summaries
File Description
src/Essentials/src/MediaPicker/MediaPicker.ios.cs Updates provider loading and failure cleanup.
Review details
  • Files reviewed: 1/1 changed files
  • Comments generated: 0
  • Review effort level: Lite

@kubaflo

kubaflo commented Sep 12, 2026

Copy link
Copy Markdown
Contributor Author

Superseded by automated main backport #38488, created with /backport to main on #37879. The replacement has the identical patch; closing this manually-created duplicate. The corresponding SR11 backport is #38481.

@kubaflo kubaflo closed this Sep 12, 2026

This branch was previously deployed

1 inactive deployment
copilot-pat-pool — 7ec42172 Deployed Sep 11, 2026 by kubaflo via conclusion #1877
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants