Repository navigation
[iOS] Fix MediaPicker throwing UIKitThreadAccessException when picking 2+ items - #37879
Conversation
…g 2+ items PickerResultsToMediaFiles reads PHPickerResult.ItemProvider - a UIKit call guarded by UIApplication.EnsureUIThread() - inside a loop that awaits with ConfigureAwait(false). The first iteration runs on the main thread because the picker delegate invokes it there, but LoadFileRepresentationAsync completes through a TaskCompletionSource created with RunContinuationsAsynchronously, so the continuation never runs inline. From the second iteration onwards the read happens on the thread pool and throws UIKitThreadAccessException. Read every ItemProvider before the first await, then load the file representations in a second loop. NSItemProvider is a Foundation type, so holding it across the awaits is safe. This restores the earlier behaviour of materializing all providers up front while keeping the temp-backed FullPath, which is assigned in the PHPickerFileResult constructor rather than by the load. Also disposes results that were constructed but never loaded, which the previous code leaked when a load threw.
|
🚀 Dogfood this PR with:
curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 37879Or
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 37879" |
|
Hey there @@pierre-galaup! Thank you so much for your PR! Someone from the team will get assigned to your PR shortly and we'll get it reviewed. |
|
Hey there @pierre-galaup! Thank you so much for your PR! Someone from the team will get assigned to your PR shortly and we'll get it reviewed. |
|
Azure Pipelines: Successfully started running 1 pipeline(s). There may be pipelines that require an authorized user to comment /azp run to run. |
|
@dotnet-policy-bot agree |
This comment has been minimized.
This comment has been minimized.
MauiBot
left a comment
There was a problem hiding this comment.
Expert Review — 1 findings
See inline comments for details.
| await fileResult.LoadFileRepresentationAsync().ConfigureAwait(false); | ||
| fileResults.Add(fileResult); | ||
| fileResult = null; | ||
| pickerResults.Add(new PHPickerFileResult(file.ItemProvider)); |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[moderate] iOS/MacCatalyst Platform Specifics — Hoisting the whole PHPickerFileResult construction (not just the file.ItemProvider read) into the pre-await loop moves per-item native + filesystem work onto the main thread for every selected item.
The constructor does, per item: provider.RegisteredTypeIdentifiers (NSArray→string[] marshal) with three LINQ passes over it, UTType.CopyAllTags via GetFileExtension, provider.SuggestedName, and CreateTemporaryFilePath → Directory.CreateDirectory (a synchronous filesystem syscall) plus Guid.NewGuid().
Concrete scenario: PickMultipleAsync builds its PHPickerConfiguration with an unlimited/large SelectionLimit; a user selects a few hundred assets. Previously only iteration 1's constructor ran on the main thread — the await LoadFileRepresentationAsync().ConfigureAwait(false) moved iterations 2..N onto the thread pool. Now all N constructions run synchronously on the UI thread while the picker is being dismissed, so the dismissal hitch scales linearly with selection count.
The fix's stated intent only requires the ItemProvider property read to happen before the first continuation. A minimal form keeps that guarantee without relocating the I/O — capture the providers up front (var providers = new NSItemProvider[results.Length]; for (var i = 0; i < results.Length; i++) providers[i] = results[i].ItemProvider;) and keep constructing PHPickerFileResult inside the existing load loop. That also drops the need for the first try/catch and its dispose loop, since capturing a reference cannot leave a half-built disposable behind.
MauiBot
left a comment
There was a problem hiding this comment.
AI Review Summary
@pierre-galaup — new AI review results are available based on commit
6104b98.
🗂️ Review Sessions — click to expand
🚦 Gate — Test Before & After Fix
Gate Result: ⚠️ SKIPPED
No tests were detected in this PR.
Recommendation: Add tests to verify the fix using the write-tests-agent.
📋 Pre-Flight — Context & Validation
PR #37879 Pre-Flight
Context
- PR:
[iOS] Fix MediaPicker throwing UIKitThreadAccessException when picking 2+ items - Issue: #37878, a confirmed iOS regression introduced in 10.0.100 by #35805
- Materialized branch:
pr-review-37879atda784bf2baf7c15753560d2edaa7da9bba34863f - Base:
origin/mainat90e5e934180bf2217180fea7e4b0c37d03f7514b - Changed production file:
src/Essentials/src/MediaPicker/MediaPicker.ios.cs - PR delta: 29 insertions, 7 deletions
- Target platform: iOS
Problem
PickerResultsToMediaFiles receives its PHPickerResult[] from the picker delegate on the UI thread. On the base implementation it constructs one PHPickerFileResult per loop iteration from file.ItemProvider, then awaits LoadFileRepresentationAsync().ConfigureAwait(false). PHPickerResult.ItemProvider is UIKit-thread-affine. Because the load completes a TaskCompletionSource created with RunContinuationsAsynchronously, the continuation after the first load runs on a pool thread; reading the second result's ItemProvider deterministically throws UIKitThreadAccessException.
Single selection avoids the second getter access and therefore succeeds. The regression came from #35805 changing eager materialization of all providers before the first await into sequential construction/loading, while fixing real temporary FullPath behavior.
Existing PR Approach
The PR eagerly constructs every PHPickerFileResult before the first await, then loads each representation in a second loop. It also adds disposal of both loaded and not-yet-loaded wrappers if construction or loading fails. An alternative candidate must not repeat this two-phase eager-materialization strategy and must preserve #35805's real temporary FullPath, ordering, photo/video behavior, and disposal semantics.
Validation Contract
The prior gate reported: SKIPPED - no tests detected in this PR. Do not rerun gate verification and do not create or overwrite gate/content.md. No mandatory regression-test list was supplied in the STEP 5a request.
There is no constructible PHPickerResult seam in Essentials.UnitTests, and the behavioral scenario needs a real picker on an iOS simulator/device. The sole bounded local validation command for each candidate is the PR's targeted iOS compile:
dotnet build src/Essentials/src/Essentials.csproj -f net10.0-ios26.0 --no-restore /p:BuildIpa=false /p:EnableSourceLink=false /p:UseSharedCompilation=falseThis command is compilation evidence, not a behavioral test. A candidate must therefore report Blocked, not Pass, even when compilation succeeds, unless it actually executes the real multi-selection behavior (no such detected test command is available). Do not run any full suite or unrelated tests.
Attempt Boundaries
- One implementation/compile pass and at most one focused correction/recompile.
- Modify only files permitted by
.github/.baseline-state.json; expected allow-list is the one PR production file above. - Preserve all pre-existing unrelated tracked and untracked worktree changes.
- Use only
pwsh .github/scripts/EstablishBrokenBaseline.ps1 -Restorefor restoration. - Perform the
try-fixskill's inline expert self-review; do not launch another reviewer.
🔬 Code Review — Deep Analysis
Expert PR Evaluation
Verdict
Approve with one moderate, actionable finding. The submitted fix correctly prevents
PHPickerResult.ItemProvider from being read after ConfigureAwait(false) resumes the sequential
load loop on a thread-pool thread. No blocking correctness, disposal, native-lifetime, path-safety,
or iOS/macCatalyst compatibility defect was found.
Independent assessment
The change splits PickerResultsToMediaFiles into two phases. It first constructs every
PHPickerFileResult while execution is still synchronously inside the UIKit picker completion
callback, then loads each file representation sequentially. This keeps every UIKit-affine
ItemProvider getter on the main thread while preserving result order and the temp-backed
FullPath behavior introduced by #35805.
The new failure cleanup is internally consistent:
- A construction failure disposes every wrapper that was successfully added.
- During loading,
fileResultsis exactly the successfully loaded prefix ofpickerResults.
Cleanup disposes that prefix and then disposes the failing item plus every unloaded suffix item,
without a gap or double-disposal. - Disposing an in-flight
PHPickerFileResultcancels itsNSProgress, faults its load task, and
deletes any partial temporary file.
The main-thread premise is valid for both callers. PhotoPickerDelegate.DidFinishPicking invokes
CompletedHandler from UIKit's callback path after dismissal, and each async completion method
runs synchronously through the new construction loop before its first incomplete await.
Actionable finding
Moderate - avoid moving unrelated per-item work onto the UI thread.
At src/Essentials/src/MediaPicker/MediaPicker.ios.cs:281, the PR hoists the entire
PHPickerFileResult constructor rather than only the thread-affine file.ItemProvider getter.
Each constructor marshals RegisteredTypeIdentifiers, performs several identifier scans, calls
UTType.CopyAllTags, reads SuggestedName, creates a GUID, and synchronously calls
Directory.CreateDirectory. With a large multi-selection, all of that work now runs during picker
dismissal on the main thread and can produce a linearly growing UI hitch.
The narrower refinement is to capture all NSItemProvider references on the main thread, then
construct and load one PHPickerFileResult at a time in the existing sequential loop. This retains
the threading fix, restores the prior at-most-one-unadded-wrapper lifetime invariant, and avoids
new index-partitioned cleanup.
Evidence limits
The Gate was skipped because the PR adds no detected tests. The code path requires a real
PHPickerResult, so static review can establish the mechanism and cleanup invariants but cannot
replace an iOS multi-selection behavioral run.
🛠️ Try-Fix — Analysis & Comparison
PR #37879 — Try-Fix Aggregate (STEP 5a)
Status: 2 of 2 bounded alternative-fix candidates complete.
| Candidate | Approach | Result | Compile | Findings | Artifacts |
|---|---|---|---|---|---|
| 1 | Per-iteration main-thread marshaling of the UIKit-affine ItemProvider read |
Blocked |
FAILED — NETSDK1005 before compilation | 2 (1 moderate, 1 minor) | try-fix/attempt-1/, try-fix-1/content.md |
| 2 | Capture the UIKit synchronization context across intermediate loads | Blocked |
FAILED — NETSDK1004 before compilation | 1 (moderate) | try-fix/attempt-2/, try-fix-2/content.md |
Concise evidence-based comparison
- PR #37879 eagerly materializes every provider/wrapper before awaiting. Candidate 1 instead explicitly dispatches each later getter to the main thread. Candidate 2 retains one-at-a-time construction and captures the UIKit context on intermediate load awaits, with the final await remaining off-context.
- Candidate 1's inline review recorded UI-thread-blocking deadlock exposure and N-1 explicit dispatch hops. Candidate 2 removes explicit getter dispatch, but its intermediate continuation scheduling still has a reviewed main-thread-blocking deadlock scenario.
- Neither candidate reached C# compilation: candidate 1 encountered NETSDK1005 and candidate 2 NETSDK1004, both during asset resolution. Neither ran a real iOS multi-selection behavior test, so both remain
Blocked. - No winner is selected here; STEP 5b owns final review.
Candidate 1 — Full Narrative
Final result: Blocked
Artifacts: CustomAgentLogsTmp/PRState/37879/PRAgent/try-fix/attempt-1/
Approach
Per-iteration main-thread marshaling of the UIKit-affine ItemProvider read.
The candidate keeps PickerResultsToMediaFiles's original single sequential loop exactly as it
existed at base — construct one PHPickerFileResult, await its load, add it, repeat — including
base's fileResult?.Dispose(); DisposeFileResults(fileResults); throw; failure handler. The only
change is that each file.ItemProvider read is hoisted onto the UI thread:
var itemProvider = await MainThread.InvokeOnMainThreadAsync(() => file.ItemProvider).ConfigureAwait(false);
fileResult = new PHPickerFileResult(itemProvider);MainThread is already in scope via the existing using Microsoft.Maui.ApplicationModel; (line 8),
so no new using directive is required.
Mechanism-level distinction from PR #37879
| PR #37879 | Candidate 1 | |
|---|---|---|
| Root-cause hypothesis | "The read must never straddle a continuation" | "The getter is thread-affine; run it on the main thread wherever the loop is" |
| Mechanism | Two-phase eager materialization: drain all ItemProviders into a fully-populated List<PHPickerFileResult> before the first await, then a second loop loads them |
Structure unchanged; the getter is dispatched to the UI thread per iteration via BeginInvokeOnMainThread + TaskCompletionSource |
| Loop shape | 1 → 2 loops | 1 loop (unchanged) |
| Live un-added wrappers | 0..N | always ≤ 1 (base invariant preserved) |
| Disposal handler | New index-partitioned suffix cleanup + separate construction-phase catch | Base handler unchanged |
| Size vs base | +29 / −7 | +8 / −1 (1 functional line) |
Prior approach avoided. PR #37879's shared failure mechanism is that after
await LoadFileRepresentationAsync().ConfigureAwait(false) — whose TaskCompletionSource uses
RunContinuationsAsynchronously — the method resumes on a thread-pool thread, so iteration 2+ reads
the UIKit-affine PHPickerResult.ItemProvider off-thread and deterministically throws
UIKitThreadAccessException. The PR defeats this by ensuring no read can ever occur after an await
exists. This candidate deliberately does not reuse that strategy.
Cause-to-effect chain for the candidate. On iteration 2 the method body genuinely is on a pool
thread — the candidate does not try to prevent that. But the ItemProvider getter no longer executes
inline there. MainThread.InvokeOnMainThreadAsync posts the getter onto the UI thread via
BeginInvokeOnMainThread, awaits its TaskCompletionSource, and returns the already-materialized
NSItemProvider reference. Because the UIKit call is physically performed on the UI thread, the
thread-affinity check that produced UIKitThreadAccessException is never reached — independently of
where the enclosing loop resumed. Since the crash is neutralized at the call site rather than by
restructuring, the awaited-loop shape, per-item lifetime, and base's disposal shape need no change.
MainThread.InvokeOnMainThreadAsync<T>(Func<T>) (src/Essentials/src/MainThread/MainThread.shared.cs
line 111) short-circuits to Task.FromResult(func()) when IsMainThread is true, so iteration 1 —
which still runs on the picker delegate's main thread — incurs zero dispatch cost. The hop only
materializes for the iterations that actually resumed on the pool, i.e. exactly the crashing case.
Preservation of required behavior. Ordering (sequential foreach over results), #35805's
temp-backed real FullPath, photo/video handling, rotation, compression, and DisposeFileResults
semantics are all byte-for-byte untouched. Because at most one un-added wrapper exists at a time,
base's fileResult?.Dispose() handler remains exactly correct; the PR must add an index-partitioned
suffix-cleanup loop precisely because eager materialization can leave an arbitrary suffix of
constructed-but-unloaded wrappers.
Files changed
src/Essentials/src/MediaPicker/MediaPicker.ios.cs(+8 / −1 vs base) — the sole baseline-allow-listed
production file in PR #37879.
Full candidate diff
Measured against PR base 90e5e934180bf2217180fea7e4b0c37d03f7514b (origin/main), i.e. this is the
standalone candidate fix, not a delta on top of the PR's fix.
diff --git a/src/Essentials/src/MediaPicker/MediaPicker.ios.cs b/src/Essentials/src/MediaPicker/MediaPicker.ios.cs
index 5f08ab3b4e..75ae4ffb98 100644
--- a/src/Essentials/src/MediaPicker/MediaPicker.ios.cs
+++ b/src/Essentials/src/MediaPicker/MediaPicker.ios.cs
@@ -275,7 +275,14 @@ namespace Microsoft.Maui.Media
{
foreach (var file in results)
{
- fileResult = new PHPickerFileResult(file.ItemProvider);
+ // PHPickerResult.ItemProvider is a UIKit-thread-affine getter. This method starts
+ // on the main thread (it is invoked from the picker delegate), but the awaited load
+ // below uses ConfigureAwait(false), so every iteration after the first resumes on a
+ // thread-pool thread. Marshal the getter itself onto the main thread so it is always
+ // evaluated where UIKit allows it, regardless of where the loop resumed.
+ var itemProvider = await MainThread.InvokeOnMainThreadAsync(() => file.ItemProvider).ConfigureAwait(false);
+
+ fileResult = new PHPickerFileResult(itemProvider);
await fileResult.LoadFileRepresentationAsync().ConfigureAwait(false);
fileResults.Add(fileResult);
fileResult = null;Surrounding context after the change (unchanged base code, shown for review):
var fileResults = new List<FileResult>(results.Length);
PHPickerFileResult fileResult = null;
try
{
foreach (var file in results)
{
var itemProvider = await MainThread.InvokeOnMainThreadAsync(() => file.ItemProvider).ConfigureAwait(false);
fileResult = new PHPickerFileResult(itemProvider);
await fileResult.LoadFileRepresentationAsync().ConfigureAwait(false);
fileResults.Add(fileResult);
fileResult = null;
}
}
catch
{
fileResult?.Dispose();
DisposeFileResults(fileResults);
throw;
}Compile command and result
Exact command (the only permitted build/test validation):
dotnet build src/Essentials/src/Essentials.csproj -f net10.0-ios26.0 --no-restore /p:BuildIpa=false /p:EnableSourceLink=false /p:UseSharedCompilation=falseResult: FAILED (exit code 1) after 0.49 s — environmental, not code-related.
error NETSDK1005: Assets file '/Users/cloudtest/vss/_work/1/s/artifacts/obj/Essentials/project.assets.json'
doesn't have a target for 'net10.0-ios26.0'. Ensure that restore has run and that you have included
'net10.0-ios26.0' in the TargetFrameworks for your project.
[.../src/Essentials/src/Essentials.csproj::TargetFramework=net10.0-ios26.0]
Build FAILED.
0 Warning(s)
1 Error(s)
Time Elapsed 00:00:00.49
Full log: .../attempt-1/test-output.log.
The failure occurs in Microsoft.PackageDependencyResolution.targets during NuGet asset resolution,
before any C# is compiled. It emits 0 warnings and 1 SDK-level error that does not reference the
changed file, and it is reproducible independently of the edit. The attempt is explicitly forbidden
from running dotnet restore or any other build command, so the single permitted focused
correction/recompile could not address it and was therefore not spent. No compilation evidence was
obtained for this candidate.
Behavioral-validation limitation
- The prior gate was SKIPPED — no tests detected in this PR; it was not rerun and
gate/content.md
was not created or modified. - No mandatory regression tests were supplied, and there is no constructible
PHPickerResultseam in
Essentials.UnitTests. Reproducing the bug requires a realPHPickerViewControllermulti-selection
on an iOS simulator/device, which is outside the bounded validation contract. - Per the pre-flight validation contract, the bounded command is compilation evidence only, never
behavioral success. Therefore this candidate could not reportPasseven if it had compiled
cleanly.
Final result: Blocked
Three independent conditions each force Blocked:
- Baseline could not be established.
EstablishBrokenBaseline.ps1fail-fasts on a dirty working
directory (.github/scripts/EstablishBrokenBaseline.ps1line 392). The worktree contains ~45
pre-existing harness-owned modified tracked files under.github/scripts/,.github/skills/,
andeng/scripts/. These are not attempt-created drift, and cleaning, committing, or reverting
them is forbidden..github/.baseline-state.jsonwas consequently never written, so there was no
RevertedFilesallow-list and no script-restorable state. - No compilation evidence — NETSDK1005, above.
- No behavioral validation possible — the validation contract mandates
Blockedregardless.
Not Fail: the build failure is an SDK asset-resolution problem, not a defect in the candidate code.
Failure / blocker analysis
Primary blocker — baseline. Because the baseline script could not run, the standard
revert-to-broken-state workflow was unavailable. Mitigation used, chosen to honor every restoration
rule: the single allow-listed production file (confirmed by pre-flight as the only production file in
PR #37879) was byte-snapshotted to attempt-1/MediaPicker.ios.cs.orig (SHA256
BF265BCF32CCEE36A7A130916912E3A884E46C3519616D4444C214C7C07955ED) before editing, and restored
afterwards by a plain filesystem copy of that snapshot. No git checkout, git restore,
git reset, git clean, git stash, rm, or Remove-Item was used at any point, and no
pre-existing tracked or untracked path was modified or deleted.
Because baseline was not applied, the file on disk still held the PR's fix, so the candidate was
implemented by replacing the PR's two-phase block. The resulting file content equals
base + candidate, which is why fix.diff is recorded against base 90e5e934 (the true candidate
patch) with the raw git diff (candidate vs PR fix) preserved separately as fix-vs-pr-head.diff.
Secondary blocker — compile. artifacts/obj/Essentials/project.assets.json has no net10.0-ios26.0
target in this worktree. Candidate 2 will hit the identical NETSDK1005 wall, so compile evidence is
equally unavailable to both candidates and cannot be used to discriminate between them.
Self-review
Performed inline against .github/agents/maui-expert-reviewer.md (Overarching Principles + the
always-active Logic and Correctness / Regression Prevention / Complexity Reduction dimensions +
Threading and Async routing for .ios.cs). No sub-agent was spawned.
Findings count: 2 — 0 critical, 0 major, 1 moderate, 1 minor.
[moderate] Threading and Async— marshaling the read back to the UI thread introduces a
main-thread dependency the base code lacked. Concrete scenario: an app that synchronously blocks
the UI thread on the picker task (PickPhotosAsync().Resultfrom a main-thread handler) would
previously fault withUIKitThreadAccessExceptionbut would now deadlock, since
BeginInvokeOnMainThreadcan never drain. Mitigating factors:PHPickerpresentation and
PHPickerFileResult.LoadFileRepresentationAsyncalready require a live main run loop, and the
public API is async-only, so blocking callers are already unsupported. Accepted, not fixed.
This is the principal mechanism-level risk differentiating this candidate from the PR, and is the
main item a human reviewer should weigh.[minor] Complexity Reduction / Performance— up to N−1 main-thread dispatch hops for N selected
items; iteration 1 short-circuits via theIsMainThreadfast path, and remaining hops are dwarfed
by the per-item file-representation load. Accepted.
No [critical] or [major] findings, so no pre-test correction round was triggered. Step 7.5 drift
check confirmed the diff was unchanged after the test step, so the recorded findings reflect the final
diff. Persisted as reviewer-findings.json / reviewer-findings.diff.
Restore outcome
pwsh .github/scripts/EstablishBrokenBaseline.ps1 -Restore→Restored: False,
Message: No baseline state found. This is the expected no-state completion, because Step 2 never
created.github/.baseline-state.json.- Snapshot restore verified:
src/Essentials/src/MediaPicker/MediaPicker.ios.csSHA256 is
BF265BCF32CCEE36A7A130916912E3A884E46C3519616D4444C214C7C07955ED— identical to the pre-edit
snapshot. git status --porcelain -- src/Essentials/src/MediaPicker/MediaPicker.ios.cs→ empty (clean).git status --porcelain --untracked-files=no -- src/→ empty (zero tracked drift anywhere undersrc/).- All pre-existing harness-owned modifications under
.github/andeng/were left exactly as found.
The worktree is clean of attempt-created changes and is ready for candidate 2.
PR #37879 — STEP 5a Candidate 2 (try-fix attempt-2)
Final result: Blocked
Artifacts: /Users/cloudtest/vss/_work/1/s/CustomAgentLogsTmp/PRState/37879/PRAgent/try-fix/attempt-2/
Approach
Preserve the UIKit synchronization context between items, but not after the final item.
The candidate keeps one sequential loading loop and the base implementation's one-live-wrapper disposal
invariant. It changes the foreach to an indexed for so each load await can tell whether another
PHPickerResult.ItemProvider getter remains. Intermediate awaits use
ConfigureAwait(i < results.Length - 1), which is true; the continuation returns through the UIKit
synchronization context before reading the next provider. The final await evaluates the expression to
false, preserving the base behavior of continuing later rotation/compression work off that context.
Mechanism-level distinction from both prior approaches
| PR #37879 | Candidate 1 | Candidate 2 | |
|---|---|---|---|
| Mechanism | Read every provider and construct every wrapper synchronously before the first await; load in a second loop | Resume off-thread, then explicitly call and await MainThread.InvokeOnMainThreadAsync around each getter |
Make each intermediate load continuation resume on the already-current UIKit context; read the next getter naturally there |
| Loop/lifetime | Two loops; 0..N unadded wrappers can be live | One loop; at most one unadded wrapper | One loop; at most one unadded wrapper |
| UI scheduling | No UI dependency after eager materialization | Explicit getter dispatch after each intermediate load | Implicit context capture on each intermediate load; no explicit getter dispatch |
| Final-load continuation | Off-context | Off-context | Off-context |
PR mechanism avoided. This candidate does not eagerly materialize providers or wrappers. A wrapper is
created only when its sequential loop iteration starts, so the PR's two-phase collection and suffix
cleanup are unnecessary.
Candidate 1 mechanism avoided. This candidate never invokes MainThread.InvokeOnMainThreadAsync and
never separately awaits a dispatched getter. The causal chain is instead: the native picker completion
enters on the UIKit thread → an intermediate file load captures that current synchronization context →
its continuation is posted back through that context → only then does the next iteration evaluate
results[i].ItemProvider. Thus the UIKit getter executes on the correct thread without candidate 1's
explicit per-getter dispatch call. This still creates a main-thread continuation dependency, recorded by
the inline review below.
Preserved behavior. Array-index iteration retains result order. Wrapper creation,
LoadFileRepresentationAsync, photo/video provider behavior, #35805's real temporary FullPath, later
rotation/compression, and the base catch block's fileResult?.Dispose() plus
DisposeFileResults(fileResults) semantics remain unchanged. For one result, the conditional is false,
matching base scheduling because no later UIKit getter exists.
Files changed
src/Essentials/src/MediaPicker/MediaPicker.ios.cs(+3 / -2 versus base) — the sole path in the clean
worktree baseline state'sRevertedFiles;NewFileswas empty.
Full candidate diff
Measured against merge base 90e5e934180bf2217180fea7e4b0c37d03f7514b:
diff --git a/src/Essentials/src/MediaPicker/MediaPicker.ios.cs b/src/Essentials/src/MediaPicker/MediaPicker.ios.cs
index 5f08ab3b4e..e73ff34886 100644
--- a/src/Essentials/src/MediaPicker/MediaPicker.ios.cs
+++ b/src/Essentials/src/MediaPicker/MediaPicker.ios.cs
@@ -273,10 +273,11 @@ namespace Microsoft.Maui.Media
PHPickerFileResult fileResult = null;
try
{
- foreach (var file in results)
+ for (var i = 0; i < results.Length; i++)
{
- fileResult = new PHPickerFileResult(file.ItemProvider);
- await fileResult.LoadFileRepresentationAsync().ConfigureAwait(false);
+ fileResult = new PHPickerFileResult(results[i].ItemProvider);
+ // Preserve the UIKit synchronization context only while another ItemProvider remains to be read.
+ await fileResult.LoadFileRepresentationAsync().ConfigureAwait(i < results.Length - 1);
fileResults.Add(fileResult);
fileResult = null;
}Compile command and outcome
The exact permitted command was run once in the clean worktree:
dotnet build src/Essentials/src/Essentials.csproj -f net10.0-ios26.0 --no-restore /p:BuildIpa=false /p:EnableSourceLink=false /p:UseSharedCompilation=falseOutcome: FAILED before C# compilation (exit code 1, 0.41 s).
error NETSDK1004: Assets file '.../pr37879-candidate2/artifacts/obj/Essentials/project.assets.json' not found. Run a NuGet package restore to generate this file.
Build FAILED.
0 Warning(s)
1 Error(s)
Time Elapsed 00:00:00.41
This is a known restore/assets environment failure in Microsoft.PackageDependencyResolution.targets;
it does not reference the changed source. The constraints prohibit restore/install and prohibit retrying
a known environment error, so no correction or second invocation was made. Full output is in
attempt-2/test-output.log; no compilation evidence was obtained.
Behavioral-test limitation
The earlier gate was SKIPPED — no tests detected and was not rerun or modified. No mandatory
regression tests were supplied. The only available command was a compile, not a real iOS
PHPickerViewController multi-selection test, and the clean worktree could not reach compilation due to
missing assets. Therefore the candidate cannot establish that selecting 2+ items avoids
UIKitThreadAccessException; compilation would not have constituted behavioral success even if it had
succeeded.
Final result: Blocked
- The build was blocked before compilation by missing NuGet assets (NETSDK1004).
- No actual multi-selection behavioral test exists in the bounded validation contract.
- Per the explicit contract, absence of behavioral validation requires
Blocked, neverPass.
This is not classified as a code-caused Fail: the sole command did not compile or execute candidate
code. The approach remains unproven rather than validated.
Inline expert self-review
Performed inline against .github/agents/maui-expert-reviewer.md: all eight Overarching Principles;
always-active Logic and Correctness, Regression Prevention, and Complexity Reduction; routed Input and
Path Correctness; Async and Threading Safety; and iOS/macCatalyst platform checks. No reviewer or other
agent was launched. Step 7.5 confirmed the final diff was byte-identical to the reviewed snapshot.
Findings count: 1 — 0 critical, 0 major, 1 moderate, 0 minor.
[moderate] Async and Threading Safetyat changed line 280: intermediate loads now require the UIKit
synchronization context to run their continuations. Concrete scenario: if application code
synchronously blocks the main thread on the still-running picker task after selection while another
item remains, the continuation cannot run and the picker task deadlocks. The PR's eager approach has
no main-thread dependency after initial materialization. Accepted for this alternative; no
critical/major correction was triggered.
The missing behavioral regression test is also the explicit validation blocker above. Findings are
persisted in reviewer-findings.json; reviewer-findings.diff matches fix.diff.
Baseline and restore outcome
- Baseline command in the clean worktree established merge-base
90e5e934, reverted exactly
src/Essentials/src/MediaPicker/MediaPicker.ios.cs, and wrote a state containing that one
RevertedFilesentry withNewFiles: []. - Required exact restore command:
pwsh .github/scripts/EstablishBrokenBaseline.ps1 -Restore. - Exact confirmation:
Restored True,RestoredFilescontained
src/Essentials/src/MediaPicker/MediaPicker.ios.cs, and the script printedBaseline restored. - Post-restore verification: target status empty; tracked
src/status empty; target diff versusHEAD
empty;.github/.baseline-state.jsonremoved. - The clean worktree remains registered and present as required.
🏁 Report — Final Recommendation
⚠️ Final Recommendation: REQUEST CHANGES
Winner: pr-plus-reviewer
pr-plus-reviewer best preserves the submitted fix's deterministic threading guarantee while
addressing the expert reviewer's only actionable concern. It captures every UIKit-affine
ItemProvider on the main thread, but defers full PHPickerFileResult construction so a large
selection does not synchronously marshal identifiers and perform filesystem setup for every item
during picker dismissal.
Comparative ranking
| Rank | Candidate | Mechanism | Validation | Assessment |
|---|---|---|---|---|
| 1 | pr-plus-reviewer |
Eagerly capture only NSItemProvider references; construct/load sequentially |
Blocked before C# compilation by candidate-local NETSDK1004; Gate skipped |
Strongest design: fixes the crash, removes the submitted PR's scalable main-thread work, retains simple ownership, and adds no post-dismissal UI scheduling dependency |
| 2 | pr |
Eagerly construct all wrappers, then load sequentially | Gate skipped; author reports successful iOS/macCatalyst builds and a real iOS multi-selection run | Correct and leak-safe per expert review, but moves every wrapper constructor's native marshalling and synchronous directory access onto the UI thread |
| 3 | try-fix-1 |
Dispatch each later ItemProvider getter through MainThread.InvokeOnMainThreadAsync |
Blocked before C# compilation by NETSDK1005; no behavioral test |
Mechanically plausible, but adds up to N-1 UI dispatches and a post-dismissal main-thread dependency with a reviewed sync-over-async deadlock mode |
| 4 | try-fix-2 |
Capture the UIKit synchronization context for intermediate load continuations | Blocked before C# compilation by NETSDK1004; no behavioral test |
Smallest diff, but correctness depends on synchronization-context capture and it retains the same reviewed main-thread dependency/deadlock mode |
No candidate ran a trusted regression test, so no candidate receives a passing-regression-test
advantage. The three alternative candidates were environmentally blocked rather than shown to fail
the behavior. The raw PR has the strongest author-reported runtime evidence, but the trusted Gate was
SKIPPED, so that evidence does not remove the coverage uncertainty.
Expert review reconciliation
The single expert review found no blocking correctness, disposal, native-lifetime, path-safety, or
iOS/macCatalyst issue in the submitted PR. Its one moderate finding was the avoidable UI-thread work
at MediaPicker.ios.cs:281. pr-plus-reviewer directly narrows the eager phase to the only
thread-affine operation and restores the original at-most-one-unadded-wrapper cleanup invariant.
Prior review and CI reconciliation
The public PR currently has no top-level reviews or inline review comments. All six PR issue
comments were scanned and none contains a prior error-level review finding.
gh pr checks --required could not identify required checks because the CLI is unauthenticated.
Anonymous metadata for remote PR HEAD 6104b983f32852aa7ed3bfb352e592d036a7ab2e reports 38 check
runs: maui-pr and all listed build/integration jobs completed successfully, with only the unrelated
Bump global.json job skipped. Required-check classification therefore remains unavailable, and the
trusted Gate remains SKIPPED because no PR tests were detected. Confidence in behavioral coverage
is low even though the available CI is green.
Required change
Apply pr-plus-reviewer/reviewer.patch to the submitted PR and rerun the targeted iOS build in a
restored environment. A real two-or-more-item iOS picker run remains the only direct behavioral
verification of the regression.
📱 UI Tests — Button,Label,Layout
Detected UI test categories: Button,Label,Layout
❌ Deep UI tests — 354 passed, 1 failed, 8 skipped across 3 categories on platform-pool agent (replaces in-process counts above).
🧪 UI Test Execution Results (deep, platform pool)
| Category | Tests | Snapshot diffs |
|---|---|---|
Button |
71/72 (1 skipped) ✓ | — |
Label |
90/92 (2 skipped) ✓ | — |
Layout |
193/199 (1 ❌, 5 skipped) | — |
🔍 AI analysis of failures — PR-related vs unrelated
🔍 AI-generated triage (GitHub Copilot CLI) — a heuristic judgement of whether each deep UI test failure is connected to this PR's changes. Verify before relying on it.
Likely unrelated: the failures appear pre-existing, flaky, or infrastructure.
- ● Unrelated — Editor scrolling layout (~1 test):
EditorsScrollingPageTestdoes not exercise the iOS MediaPicker code changed by this PR, and the generic Appium element-lookup failure contains no MediaPicker path.
Strongest signal: the run platform overlaps the PR's iOS scope, but the failing test's functional area does not.
❌ Layout — 1 failed test
EditorsScrollingPageTest
OpenQA.Selenium.NoSuchElementException : An element could not be located on the page using the given search parameters.; For documentation on this error, please visit: https://www.selenium.dev/documentation/webdriver/troubleshooting/errors#no-such-element-exception
at OpenQA.Selenium.WebDriver.UnpackAndThrowOnError(Response errorResponse, String commandToExecute)
at OpenQA.Selenium.WebDriver.ExecuteAsync(String driverCommandToExecute, Dictionary`2 parameters)
at OpenQA.Selenium.Appium.AppiumDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
at OpenQA.Selenium.WebDriver.FindElement(String mechanism, String value)
at OpenQA.Selenium.Appium.AppiumDriver.FindElement(String by, String value)
at OpenQA.Selenium.Appium.MobileBy.FindElement(ISearchContext context)
at OpenQA.Selenium.WebDriver.FindElement(By by)
at OpenQA.Selenium.Appium.AppiumDriver.FindElement(By by)
at Microsoft.Maui.TestCases.Tests.KeyboardScrolling.CloseiOSEditorKeyboard(AppiumDr
...
📎 Download drop-deep-uitests artifact (TRX + snapshot diffs)
🧭 Next Steps — reviewer changes required
The reviewer-enhanced candidate identified changes that are not yet in the submitted PR.
Why: pr-plus-reviewer preserves the submitted fix's main-thread ItemProvider capture while avoiding eager construction of every wrapper on the UI thread. Its targeted build was environmentally blocked before C# compilation, but code review found it safer than the raw PR and both try-fix alternatives.
Address the actionable findings in this review before merging.
aec6514 to
dbad377
Compare
…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
…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
…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
…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
…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
…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
…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
|
/backport to release/10.0.1xx-sr11 |
|
Started backporting to |
|
/backport to main |
|
Started backporting to |
… picking 2+ items (#38488) Backport of #37879 to main /cc @kubaflo @pierre-galaup Co-authored-by: Pierre Galaup <pierregalaup@outlook.fr> Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
…essException when picking 2+ items (#38481) Backport of #37879 to release/10.0.1xx-sr11 /cc @kubaflo @pierre-galaup Co-authored-by: Pierre Galaup <pierregalaup@outlook.fr>
Description of Change
PickerResultsToMediaFilesreadsPHPickerResult.ItemProvider— a UIKit call guarded byUIApplication.EnsureUIThread()— inside a loop that awaits withConfigureAwait(false):The first iteration runs on the main thread, because the picker delegate invokes it from the dismissal completion. But
LoadFileRepresentationAsynccompletes through aTaskCompletionSource<bool>created withTaskCreationOptions.RunContinuationsAsynchronously, so the continuation never runs inline. From the second iteration onwards the read happens on the thread pool and throwsUIKitThreadAccessException. 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 everyItemProviderwas read before the first await — with the loop above.Change: read every
ItemProviderup front, before the first await, then load the file representations in a second loop.NSItemProvideris 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:
FullPathis assigned in thePHPickerFileResultconstructor viaCreateTemporaryFilePath, 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— cleandotnet 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 errorsdotnet build src/Essentials/src/Essentials.csproj -f net10.0-maccatalyst26.0 --no-restore /p:EnableSourceLink=false /p:UseSharedCompilation=false— 0 warnings, 0 errorsMicrosoft.Maui.Essentials.dllinto the repro app from the issue, so the real fixed code was exercised throughMediaPicker.Default.PickPhotosAsync:FileResult.FullPathexists, is non-empty, andFile.Copy(result.FullPath, ...)succeeds — i.e. the MediaPicker.PickVideosAsync returns only file names as file path and doesn't compress the videos anymore under iOS #32832 scenario that [iOS] Fix MediaPicker FullPath for PHPicker results #35805 fixed still worksNo unit test is included: the affected path needs a real
PHPickerResult, which cannot be constructed inEssentials.UnitTests. Happy to add coverage if you can point me at a suitable seam.Issues Fixed
Fixes #37878