Repository navigation
Enable Runtime Async for .NET 12 projects - #40824
Conversation
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
🔵 Needs a closer look
Code-generation changes span libraries and consumer apps, but supplied validation covers only Android CoreCLR, leaving Apple/Windows NativeAOT execution and nondefault XamlC rewriting compatibility unverified.
No open issues 🎉
What changed in this PR
Enables Runtime Async by default for .NET 12 MAUI compilation, covering both repository projects and applications using the packaged MAUI SDK.
Changes:
- Adds framework-scoped compiler defaults while leaving .NET 11 and .NET Standard assets unchanged.
- Preserves existing
runtime-asyncselections and supports opting out withUseRuntimeAsync=false. - Adds integration tests for framework scoping and opt-out behavior in repository and generated template projects.
| File | Description |
|---|---|
src/Workload/Microsoft.Maui.Sdk/Sdk/BundledVersions.in.targets |
Adds the Runtime Async default for current-framework SDK consumers. |
src/TestUtils/src/Microsoft.Maui.IntegrationTests/SimpleTemplateTest.cs |
Tests generated MAUI projects for framework scoping and opt-out behavior. |
src/TestUtils/src/Microsoft.Maui.IntegrationTests/DotNetProjectTests.cs |
Tests repository projects across current, legacy, and .NET Standard targets. |
Directory.Build.targets |
Adds the framework-scoped Runtime Async default for repository builds. |
Review effort: Balanced
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
| <Import Project="Sdk.targets" Sdk="Microsoft.DotNet.Arcade.Sdk" /> | ||
|
|
||
| <!-- Keep Runtime Async scoped to the current .NET TFM so legacy and .NET Standard assets remain compatible. --> | ||
| <PropertyGroup Condition="$(TargetFramework.StartsWith('$(_MauiDotNetTfm)')) and !$([System.String]::Copy('$(Features)').Contains('runtime-async='))"> |
| <MauiVersion Condition=" '$(MauiVersion)' == '' ">$(MauiWorkloadVersion)</MauiVersion> | ||
|
|
||
| <!-- Default net12 MAUI projects to Runtime Async while allowing an explicit project or command-line opt-out. --> | ||
| <Features Condition="$([MSBuild]::VersionEquals($(TargetFrameworkVersion), $(MauiWorkloadTargetFrameworkVersion))) and !$([System.String]::Copy('$(Features)').Contains('runtime-async='))">runtime-async=on;$(Features)</Features> |
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
| <MauiVersion Condition=" '$(MauiVersion)' == '' ">$(MauiWorkloadVersion)</MauiVersion> | ||
|
|
||
| <!-- Default net12 MAUI projects to Runtime Async while allowing an explicit project or command-line opt-out. --> | ||
| <Features Condition="$([MSBuild]::VersionEquals($(TargetFrameworkVersion), $(MauiWorkloadTargetFrameworkVersion))) and !$([System.String]::Copy('$(Features)').Contains('runtime-async='))">runtime-async=on;$(Features)</Features> |
There was a problem hiding this comment.
[moderate] Regression Prevention and Test Coverage - The new framework and feature-precedence guards have no discriminating regression coverage. SimpleTemplateTest.Build checks build success without supplying runtime-async=off, and DotNetProjectTests only evaluates workload paths; neither asserts Features. These tests cannot detect an opt-out being overwritten or the default leaking into net11/netstandard. Add property-evaluation assertions for both this packaged default and Directory.Build.targets: net12 defaults on, a project-defined runtime-async=off remains off, and net11/netstandard remain unchanged. The manual evaluation described in the PR does not provide repeatable CI coverage for these negative branches.
#40844) <!-- copilot-assessment:v1 --> ### Agent assessment Self-reported assessment, not an independent review. Assessed revision: `21f7caeb2041cdcf0382a632dca83e4a49365107` | Dimension | Assessment | Rationale | |---|---|---| | Change confidence | 9.5/10 | ↑ On current `main` the project fails to build with the same two xUnit1051 errors as CI. With this change it builds with no warnings, and all 157 tests pass in Debug and Release.<br>↑ Test-only change. The assertions are unchanged.<br>↓ Validated locally on macOS only. CI on this PR is pending. | | Diagnosis confidence | 10/10 | ↑ The analyzer errors name both calls, and restoring `main`'s version of the file reproduces them.<br>↑ #40661 moved the project to xUnit v3 after the branch of #40819 was created. | | Evidence fit | 10/10 | ↑ These two errors are the only failure in the four failed Run Unit Tests legs of maui-pr build 1704463, the PR build of #40819. Every other test project passed in all four legs. | <!-- /copilot-assessment --> <!-- Please let the below note in for people that find this PR --> > [!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](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from this PR and let us know in a comment if this change resolves your issue. Thank you! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). The break is on `main`, where both #40819 and #40661 landed. For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change <!-- Enter description of the fix in this section --> `Controls.BindingSourceGen.UnitTests` doesn't build on `main`: ``` MayNotifyPropertyChangedTests.cs(51,5): error xUnit1051: Calls to methods which accept CancellationToken should use TestContext.Current.CancellationToken to allow test cancellation to be more responsive. MayNotifyPropertyChangedTests.cs(67,16): error xUnit1051: Calls to methods which accept CancellationToken should use TestContext.Current.CancellationToken to allow test cancellation to be more responsive. ``` #40819 added `MayNotifyPropertyChangedTests` on a branch created before #40661 moved the unit tests to xUnit v3. The xUnit v3 analyzers report these two calls as errors. The PR build of #40819 ([maui-pr 1704463](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1704463)) failed the four Run Unit Tests legs (Windows and macOS, Debug and Release) for this reason only. The PR was merged with those legs red. Until this is fixed, they fail on `main` and in every PR build that merges `main`. `Controls.Core.UnitTests` also fails on `main`, for an unrelated reason. 31 async leak tests have failed since #40824, whose own PR build [1704502](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1704502) failed them on all four unit-test legs. This PR doesn't fix those, so the unit-test legs stay red until they're fixed too. This passes `TestContext.Current.CancellationToken` to `CSharpSyntaxTree.ParseText` and `Compilation.GetDiagnostics`, as the other tests in the project already do. The assertions don't change. Validation on macOS arm64 with the pinned SDK 12.0.100-alpha.1.26523.103: | Command | Result | | --- | --- | | `dotnet build src/Controls/tests/BindingSourceGen.UnitTests/Controls.BindingSourceGen.UnitTests.csproj -c Debug -p:MauiPlatforms= -p:IncludePreviousTfms=false`, with `main`'s version of the test file | Failed with the two errors above | | The same command with this change, with `-c Debug` and with `-c Release` | Succeeded, 0 warnings | | `dotnet test --project src/Controls/tests/BindingSourceGen.UnitTests/Controls.BindingSourceGen.UnitTests.csproj -c Debug --no-build`, and the same with `-c Release` | Passed, 157 of 157 in each | ### Issues Fixed <!-- Please make sure that there is a bug logged for the issue being fixed. The bug should describe the problem and how to reproduce it. --> No issue is filed. This fixes the build break on `main` from #40819. ### Let AI finish this PR - [ ] **Let the MAUI agent address review feedback and fix remaining issues on this PR.** Maintainers still decide whether it is merged. For PRs from forks, keep "Allow edits by maintainers" on so the agent can push to your branch; otherwise it opens a follow-up PR that keeps your commits. <!-- Verify the target branch follows the release workflow in docs/ReleaseBranchWorkflow.md. Infrastructure and documentation changes should target the branch where they apply. --> Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
#40856) <!-- copilot-assessment:v1 --> ### Agent assessment Self-reported assessment, not an independent review. Assessed revision: `cecdfd482a7c8c2281a8e086f7782d553eb23efa` | Dimension | Assessment | Rationale | |---|---|---| | Change confidence | 9/10 | ↑ `TypedBinding` only calls a subscriber for `OneWay` and `TwoWay` bindings, and `Mode` can't change once a binding is applied. So for a literal `OneTime` mode, the removed subscriber was dead code.<br>↑ SourceGen (940 passed) and XAML (2,341 passed) unit tests pass locally. The new generator test fails on main's generator for the `OneTime` case only.<br>↑ The assembly with the measured page shrinks by 21% (IL only) and 13% (ReadyToRun), and its first creation is faster under both JIT and ReadyToRun.<br>↓ No CI or device runs yet, because the PR pipelines are disabled. | <!-- /copilot-assessment --> <!-- Please let the below note in for people that find this PR --> > [!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](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from this PR and let us know in a comment if this change resolves your issue. Thank you! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). This is .NET 12 performance work on the compiled bindings from #40819, which is on `main`. For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change <!-- Enter description of the fix in this section --> This is a follow-up to #40819. The XAML source generator compiles each `{Binding}` with an `x:DataType` into a `TypedBinding`. Since #40819, that binding gets a subscriber lambda, which reports the objects on its path that the binding observes. A binding whose `Mode` is `OneTime` reads its path once and never observes it: `TypedBinding` only calls the subscriber for `OneWay` and `TwoWay` bindings. When `Mode` is the literal `OneTime`, the generator already leaves out the setter. Now it also leaves out the subscriber. It emits `listenerCount: 0, subscriber: null`, as it already does for a self-binding like `{Binding .}`. A `Mode` that isn't a literal, such as `{x:Static BindingMode.OneTime}`, keeps its subscriber. Generated code for `{Binding Child.Q1, Mode=OneTime}`, before: ```csharp return new global::Microsoft.Maui.Controls.Internals.TypedBinding<global::Test.TestViewModel, string?>( getter: source => (source.Child?.Q1, true), setter, listenerCount: 2, subscriber: static (global::Test.TestViewModel source, ref global::Microsoft.Maui.Controls.Internals.TypedBindingListeners listeners) => { if (source is null) return; listeners.Listen(source, "Child"); if (source.Child is not { } part1) return; listeners.Listen(part1, "Q1"); }) { Mode = extension.Mode, }; ``` After: ```csharp return new global::Microsoft.Maui.Controls.Internals.TypedBinding<global::Test.TestViewModel, string?>( getter: source => (source.Child?.Q1, true), setter, listenerCount: 0, subscriber: null) { Mode = extension.Mode, }; ``` For each `OneTime` binding, the page no longer has the lambda method and the static field that caches its delegate. It also skips allocating that delegate the first time the binding is created. #### Measurements How the measurements were made: - **Generated page.** A temporary test, which isn't part of this PR, ran the XAML source generator from main and from this PR. Its input was a page with 100 `Label`s bound with `Mode=OneTime`: 50 one-level paths like `P3` and 50 two-level paths like `Child.Q3`. The same assembly also has a small warm-up page with two `OneTime` bindings and one `OneWay` binding. The test emitted the assembly with Release optimizations. - **Timing.** A console app loaded that assembly with Release builds of MAUI. It creates the warm-up page first, so that the measured creation of the 100-binding page doesn't include MAUI's own first-use costs. Each first-creation sample is a fresh process, alternating main and this PR, with 31 pairs. - **ReadyToRun.** The ReadyToRun builds come from `dotnet publish -c Release -r osx-arm64 -p:PublishReadyToRun=true`. - **Environment.** Apple Silicon, .NET 12 (`12.0.100-alpha.1.26523.103`).  The labels on the timing charts are the median paired difference. | Measurement | main | This PR | Change | |---|---:|---:|---:| | Page assembly, IL only | 73,728 B | 58,368 B | −15,360 B (−21%) | | Page assembly, ReadyToRun | 288,256 B | 250,368 B | −37,888 B (−13%) | | Methods and fields in the page assembly | 366 and 230 | 264 and 128 | −102 each | | First creation of the page, JIT (median) | 9,085 µs | 8,269 µs | −681 µs (95% CI −975 to −460) | | First creation of the page, ReadyToRun (median) | 945 µs | 887 µs | −56 µs (95% CI −76 to −46) | | Allocated by the first creation | 648,840 B | 643,240 B | −5,600 B | Steady-state creation of the page shows no significant difference. The paired 95% confidence intervals are −32 to +73 µs per page with JIT and −160 to +101 µs with ReadyToRun, and allocations are identical at 635,224 B per page. Per `OneTime` binding, that's about 150 B of IL-only assembly and 370 B of ReadyToRun image, one method and one field less. The page assembly has 102 `OneTime` bindings: the 100 in the measured page and 2 in the warm-up page. #### Changes - `CompiledBindingMarkup.cs`: for a literal `OneTime` mode, emit `listenerCount: 0, subscriber: null` instead of the subscriber. - New theory `OnlyBindingsThatCanObserveTheirPathGetASubscriber` in the SourceGen unit tests. A literal `OneTime` mode gets no subscriber. `OneWay`, `TwoWay`, `Default`, `{x:Static BindingMode.OneTime}` and an unset mode keep theirs. - `BindingsCompiler` XAML test: a `OneTime` label keeps its first value after its source changes. This runs for the Runtime, XamlC and SourceGen inflators. #### Validation These were run on macOS arm64 with the pinned SDK. Each project was built first with `dotnet build <project> -c Debug -p:MauiPlatforms= -p:IncludePreviousTfms=false -p:PublicApiType=Validate`. | Command | Result | | --- | --- | | `dotnet test --project src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj -c Debug --no-build` | 940 passed, 71 skipped | | The same command with `--filter-method '*OnlyBindingsThatCanObserveTheirPathGetASubscriber'`, against main's generator | 1 of 6 cases failed, the `Mode=OneTime` one, as expected | | `dotnet test --project src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj -c Debug --no-build` | 2,341 passed, 8 skipped | | `dotnet format whitespace --folder --include <changed files> --verify-no-changes` | No changes | Until #40844 merges, the unit-test legs of this PR's CI will fail on `BindingSourceGen.UnitTests`. They'll also fail on the 31 leak tests from #40824 until those are fixed. ### Issues Fixed <!-- Please make sure that there is a bug logged for the issue being fixed. The bug should describe the problem and how to reproduce it. --> No issue is filed. This is a follow-up to #40819. ### Let AI finish this PR - [ ] **Let the MAUI agent address review feedback and fix remaining issues on this PR.** Maintainers still decide whether it is merged. For PRs from forks, keep "Allow edits by maintainers" on so the agent can push to your branch; otherwise it opens a follow-up PR that keeps your commits. <!-- Verify the target branch follows the release workflow in docs/ReleaseBranchWorkflow.md. Infrastructure and documentation changes should target the branch where they apply. --> Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
…#40858) <!-- copilot-assessment:v1 --> ### Agent assessment Self-reported assessment, not an independent review. Assessed revision: `2e8d9b4df24c1866e6bfcdcde07873a52eac31ae` | Dimension | Assessment | Rationale | |---|---|---| | Change confidence | 9/10 | ↑ The code moves unchanged to the base class, except that `ApplyCore` is split into helpers and two `catch` clauses per handler are merged into one with the same effect. An independent line-by-line review found no behavior change.<br>↑ Controls.Core (the same 31 known failures as main), SourceGen (934 passed), XAML (2,341 passed) and BindingSourceGen (157 passed) unit tests pass locally.<br>↑ Each value type JIT-compiles 3 methods instead of 12. The first apply of 10 value-type bindings is 60% faster with JIT and 64% faster with ReadyToRun. Steady-state times are within about 1%, and allocations are unchanged.<br>↑ In an Android app, 25 fewer methods and 6 KB less IL are JIT-compiled before the first frame.<br>↓ No CI or device test runs yet, because the PR pipelines are disabled.<br>↓ NativeAOT and iOS weren't measured. | <!-- /copilot-assessment --> <!-- Please let the below note in for people that find this PR --> > [!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](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from this PR and let us know in a comment if this change resolves your issue. Thank you! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). This is .NET 12 performance work on the compiled bindings from #40819, which is on `main`. For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change <!-- Enter description of the fix in this section --> This is a follow-up to #40819. The runtime compiles the methods of a generic class again for every value type that the class is instantiated with. `TypedBinding<MyViewModel, bool>`, `TypedBinding<MyViewModel, double>`, `TypedBinding<MyViewModel, DateTime>` and every enum each get their own code, while reference types share one copy. ReadyToRun can't precompile most of these instantiations. MAUI's own image only has the ones that MAUI uses itself, and Android's default partial ReadyToRun only compiles the methods in MAUI's startup profiles. So the first time a compiled binding reads a value type, the JIT compiles 12 methods of `TypedBinding<TSource, TProperty>` for it: - 9 when the binding is first applied: `.ctor`, `Apply`, `ApplyToResolvedSource`, `ApplyCore`, `CacheDefaultValue`, `ClearAncestryChangeSubscriptions`, `GetSourceValue`, `Settle` and `Unapply`. - 3 when the source or the target changes: `OnSourceChanged`, `GetTargetValue` and `Apply(bool)`. Only a few lines of these methods depend on the types of the source and the value. This PR moves the state of the binding, and every method that depends on neither `TSource` nor `TProperty`, into the non-generic `TypedBindingBase`. `TypedBinding<TSource, TProperty>` keeps: - its constructors, `Clone` and `ListenToHandlers`; - a slimmer `ApplyCore`, which type-checks the source, walks the path through the subscriber or the handlers, and runs the getter; - `UpdateSource`, which runs the setter. It's a separate method, so that only `TwoWay` and `OneWayToSource` bindings compile it. The rest of `ApplyCore` moved to the base-class methods `BeginApply`, `CompleteWalk`, `UpdateTarget` and `TryGetValueForSource`. `ApplyCore` is now an abstract member of `TypedBindingBase`, which calls it. Its IL shrinks from 1,075 to 548 bytes, and from 5 exception-handling clauses to 2. The getter's and the setter's `catch (Exception ex) when (IsPathException(ex))` and the `catch` that follows it each became one `catch` that checks `IsPathException`, with the same effect. Behavior doesn't change. The steps of an apply run in the same order, with the same checks for an apply that user code superseded. There are no public API changes, and the generators and the code they generate are unchanged. `ApplyCore` still reads `_removingTarget` and `_subscriptions` directly, rather than through small helpers. crossgen2 inlines such a helper into every precompiled caller and then emits no code for the helper itself, so the JIT-compiled `ApplyCore` of a value type would have to compile the helper too. #### Measurements  The labels on the timing charts are the median paired difference. **First use, console app.** A console app referenced Release builds of MAUI from main and from this PR. It first warms MAUI up with a `string` binding that goes through the same steps. Then, for 10 value types (`bool`, `int`, `double`, `float`, `long`, `DateTime`, `TimeSpan`, `Thickness`, `FontAttributes` and `TextAlignment`), it creates a binding the way the source generators do and goes through two phases: - **First apply:** `SetBinding`, then setting the binding context. - **Updates and removal:** changing the source, changing the target, swapping the binding context, and removing the binding. The bindings are `TwoWay`, so that the setter runs too. `JitInfo` counts the methods that the main thread JIT-compiles, and runtime events list them. Each sample is a fresh process, alternating main and this PR, with 41 pairs. The app ran with IL-only MAUI assemblies (JIT) and with `dotnet publish -c Release -r osx-arm64 -p:PublishReadyToRun=true` (ReadyToRun). | Per value type | main | This PR | |---|---:|---:| | Methods JIT-compiled at the first apply | 9 | 2 (`.ctor`, `ApplyCore`) | | Methods JIT-compiled by updates and removal | 3 | 1 (`UpdateSource`), only for `TwoWay` and `OneWayToSource` | | IL that the JIT compiles | 2,233 B | 683 B | With ReadyToRun, 3 of the 10 types don't need the JIT on either branch, because MAUI's own image has their instantiations. | 10 value types, median of 41 fresh processes | main | This PR | Change | |---|---:|---:|---:| | First apply, JIT | 6,776 µs | 2,665 µs | −4,081 µs (95% CI −4,136 to −4,041), −60% | | First apply, ReadyToRun | 5,227 µs | 1,864 µs | −3,336 µs (95% CI −3,469 to −3,241), −64% | | Updates and removal, JIT | 1,144 µs | 759 µs | −372 µs (95% CI −424 to −359), −33% | | Updates and removal, ReadyToRun | 521 µs | 279 µs | −245 µs (95% CI −248 to −240), −47% | | First `string` binding, including MAUI's own first use, JIT | 8,209 µs | 8,195 µs | −57 µs (95% CI −221 to +81) | | First `string` binding, including MAUI's own first use, ReadyToRun | 5,569 µs | 5,519 µs | −89 µs (95% CI −133 to +136) | **Android.** A CollectionView app with 1,000 rows was built twice in Release for android-arm64, with MAUI's default partial ReadyToRun and startup profiles. Its rows bind with `x:DataType` to `string`, `int`, `double`, `bool`, `DateTime`, `FontAttributes` and `Color` properties. Both APKs were built from an older tree, with main's `TypedBinding.cs` and `TypedBindingListeners.cs`; the second one only swaps in this PR's `TypedBinding.cs`. The app logs `JitInfo` counters when its first frame is ready. There were 50 pairs of cold starts, in ABBA order, on an API 35 arm64 emulator. | Before the first frame, median of 50 cold starts | main | This PR | Change | |---|---:|---:|---:| | JIT-compiled methods | 973 | 949 | −25 (95% CI −25 to −24) | | JIT-compiled IL | 73,723 B | 67,749 B | −5,976 B (−8.1%) | | JIT time | 70.8 ms | 65.7 ms | −3.8 ms (95% CI −7.8 to +0.3) | The host was heavily loaded during these runs (load average up to 34). This made the JIT time noisy, and the time to the first frame showed no significant difference. MAUI's startup profiles predate #40819. They list `ApplyCore` with its old signature, so main doesn't precompile it either. A crossgen2 map of this PR's APK shows that the moved methods that the profiles list, like `Unapply` and `ApplyToResolvedSource`, are still precompiled. The new base-class methods, like `BeginApply` and `UpdateTarget`, aren't, so they're JIT-compiled once per process until the profiles are refreshed. The numbers above include that. **Steady state.** A console app ran the same MAUI builds interleaved; each value is the best of 11 runs. | Operation | main | This PR | Change | |---|---:|---:|---:| | A `string` source property changes, path of 1 | 21.9 ns | 21.7 ns | −0.7% | | A `string` source property changes, path of 3 | 26.4 ns | 26.5 ns | +0.3% | | An `int` source property changes | 24.6 ns | 24.8 ns | +0.8% | | A `TwoWay` `double` target changes and updates the source | 64.9 ns | 65.0 ns | +0.2% | | The binding context of a path of 3 changes | 100.0 ns | 99.7 ns | −0.3% | | Create, apply and remove a `OneWay` binding, path of 1 | 256.9 ns | 258.8 ns | +0.7% | | Create, apply and remove a `OneWay` binding, path of 3 | 401.0 ns | 402.2 ns | +0.3% | | Create, apply and remove a `OneTime` binding | 130.4 ns | 129.3 ns | −0.9% | | Create, apply and remove an `int` binding | 271.2 ns | 271.8 ns | +0.2% | Allocations are identical. A rerun of the property changes with 21 pairs measured +0.18 ns for `int` and +0.78 ns for the `TwoWay` update (paired medians). This is consistent with the virtual call to `ApplyCore` and the calls to the base-class helpers. `Microsoft.Maui.Controls.dll` grows by 512 B of IL (1,773,568 to 1,774,080 B). Its osx-arm64 ReadyToRun image shrinks by 52 KB (5,236,224 to 5,184,000 B). All measurements ran on Apple Silicon with .NET 12 (`12.0.100-alpha.1.26523.103`). #### Changes - `TypedBinding.cs`: moves the state and every method that depends on neither `TSource` nor `TProperty` from `TypedBinding<TSource, TProperty>` to `TypedBindingBase`, as described above. - `TypedBindingUnitTests.cs`: `BindingDoesNotStayAliveForDeadTarget` reads the `_subscriptions` field from `TypedBindingBase`, which now declares it. #### Validation These were run on macOS arm64 with the pinned SDK. Each project was built first with `dotnet build <project> -c Debug -p:MauiPlatforms= -p:IncludePreviousTfms=false -p:PublicApiType=Validate`. | Command | Result | | --- | --- | | `dotnet test --project src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj -c Debug --no-build` | 7,684 passed, 30 skipped, 31 failed. The failures are the leak tests that #40824 broke, the same set as on main. | | `dotnet test --project src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj -c Debug --no-build` | 934 passed, 71 skipped | | `dotnet test --project src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj -c Debug --no-build` | 2,341 passed, 8 skipped | | `dotnet test --project src/Controls/tests/BindingSourceGen.UnitTests/Controls.BindingSourceGen.UnitTests.csproj -c Debug --no-build`, with #40844 applied locally | 157 passed | | `dotnet format whitespace --folder --include <changed files> --verify-no-changes` | No changes | Until #40844 merges, the unit-test legs of this PR's CI will fail on `BindingSourceGen.UnitTests`. They'll also fail on the 31 leak tests from #40824 until those are fixed. ### Issues Fixed <!-- Please make sure that there is a bug logged for the issue being fixed. The bug should describe the problem and how to reproduce it. --> No issue is filed. This is a follow-up to #40819. ### Let AI finish this PR - [ ] **Let the MAUI agent address review feedback and fix remaining issues on this PR.** Maintainers still decide whether it is merged. For PRs from forks, keep "Allow edits by maintainers" on so the agent can push to your branch; otherwise it opens a follow-up PR that keeps your commits. <!-- Verify the target branch follows the release workflow in docs/ReleaseBranchWorkflow.md. Infrastructure and documentation changes should target the branch where they apply. --> Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
<!-- copilot-assessment:v1 --> ### Agent assessment Self-reported assessment, not an independent review. Assessed revision: `de9d325cc79b6e2d256fb181d3e6b33a257f4ae7` | Dimension | Assessment | Rationale | |---|---|---| | Change confidence | 9/10 | ↑ Controls.Core.UnitTests had 7,901 passed, 30 skipped and 0 failed in both Debug and Release; subsequent changes are instruction-only.<br>↑ Deliberate strong-reference and stale-entry negative controls failed as expected.<br>↑ Updated leak-fixer prompt compiles with v0.86.2 in strict mode; existing action and container pins are unchanged.<br>↓ Updated-head CI has not completed; Azure DevOps results remain unverified. | | Diagnosis confidence | 9.5/10 | ↑ Heap `gcroot` for the retained Button and popped Page points through runtime-async continuation objects back to the async test frames.<br>↑ Disabling runtime async in the test assembly cleared the observed command leak-test failures. | | Evidence fit | 9.5/10 | ↑ The continuation-rooted objects are the exact weak-reference targets reported by the failing leak tests.<br>↑ The refactored tests pass while retaining their long-lived sources and still fail with deliberately introduced retention. | <!-- /copilot-assessment --> > [!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](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from this PR and let us know in a comment if this change resolves your issue. Thank you! ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change Runtime async can leave a continuation rooted by a resumed async test frame. Heap-root analysis showed those continuations keeping weak-reference test targets alive, causing GC/leak tests to fail even though the product objects were no longer reachable through their intended owners. Move objects-under-test creation into non-inlined helpers, keep expected long-lived sources alive through collection, and isolate the popped-page scenario from the async test frame. Pass `SetterSpecificityList` by reference in its helper so the test removes the entry from the same struct instance it asserts on. Document the runtime-async caveat in `.github/copilot-instructions.md`, including false-positive test-frame roots, false-negative source collection, mutable-struct copies, and negative controls. Replace the leak-fixer workflow's block-scope example with a non-inlined creation helper. Its prompt-only update preserves frontmatter and existing action/container pins; the regenerated lock file changes only the body hash. Validation: `dotnet build src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj -c Debug -v quiet -nologo -nodeReuse:false -p:ValidateXcodeVersion=false` and the matching `-c Release` build both passed. `dotnet test --project src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj -c Debug --no-build` and the matching `-c Release` test both passed (7,901 passed, 30 skipped, 0 failed). The instruction-only update was compiled with `gh-aw` v0.86.2 using `compile leak-fixer --strict --no-check-update` (passed). ### Issues Fixed N/A — follow-up to PR #40824; no linked issue. ### Let AI finish this PR - [ ] **Let the MAUI agent address review feedback and fix remaining issues on this PR.** Maintainers still decide whether it is merged. For PRs from forks, keep "Allow edits by maintainers" on so the agent can push to your branch; otherwise it opens a follow-up PR that keeps your commits. <!-- Verify the target branch follows the release workflow in docs/ReleaseBranchWorkflow.md. Infrastructure and documentation changes should target the branch where they apply. --> --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
<!-- copilot-assessment:v1 --> ### Agent assessment Self-reported assessment, not an independent review. Assessed revision: `2481e06d64f2246b4362b5b7b768ac7c531a0e64` | Dimension | Assessment | Rationale | |---|---|---| | Change confidence | 8.5/10 | ↑ The Controls.Core, BindingSourceGen, SourceGen and XAML unit tests pass locally at this revision, including the new test. The 31 Controls.Core failures, all leak tests, also fail on main without this change.<br>↑ The subscribers of C# expressions in XAML pass an `object?` local. They compile against `Listen<object>`, and their tests pass.<br>↑ Each walk through a struct allocates exactly one boxed `Rect` less. Allocations are unchanged in all 44 benchmark cases whose paths only go through objects that notify. These were measured at 4de66a2, whose measured subscribers already called `Listen<T>`.<br>↑ Copilot code review found no issues at 4de66a2.<br>↓ Code compiled against `Listen(object?)` from #40819 must be recompiled, and a hand-written call that passes a `null` literal no longer compiles.<br>↓ There are no device, UI, AOT or CI runs yet, because the PR pipelines are disabled. | <!-- /copilot-assessment --> <!-- Please let the below note in for people that find this PR --> > [!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](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from this PR and let us know in a comment if this change resolves your issue. Thank you! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). This is .NET 12 performance work on the compiled bindings from #40819, which is on `main`. For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change <!-- Enter description of the fix in this section --> This is a follow-up to #40819. A compiled binding observes its path through a subscriber that the source generators emit for `SetBinding`, `BindingBase.Create` and XAML compiled bindings. The subscriber reports each object on the path with `TypedBindingListeners.Listen(object? part, string propertyName)`. The generators leave out structs that can't notify in any version, such as `DateTime`. They still report structs from other assemblies or from the app, such as `Rect`, `Point`, `Size` or `Thickness`, because some version of them could implement `INotifyPropertyChanged`. Passing such a struct as an `object` boxes it, only for the binding to find that the box can't notify. The binding runs the subscriber on every apply and whenever an observed property changes. So a binding to `Bounds.Width` allocated a boxed `Rect` (48 B) every time `Bounds` changed, the binding context changed, or the binding was applied. This replaces `TypedBindingListeners.Listen(object? part, string propertyName)` with `TypedBindingListeners.Listen<T>(T part, string propertyName)`: - For each struct type, the JIT evaluates `typeof(T).IsValueType && part is not INotifyPropertyChanged` once. A struct that can't notify occupies its position without being boxed. - If an earlier walk reported an object that notifies at that position, its handler is removed, as `Listen(object?)` did. Generated subscribers always report the same type at a given position, so this only matters for hand-written subscribers. - For reference types, the JIT removes the check, so paths through objects that notify run the same code as before. - A struct that implements `INotifyPropertyChanged` is boxed and observed, as before. The generators don't change. When subscribers are recompiled, their calls bind to `Listen<T>`. Subscribers for C# expressions in XAML store each object of the path in an `object?` local, so they call `Listen<object>`, which runs the same code as `Listen(object?)` did. `Listen(object?)` is unshipped .NET 12 API that #40819 added, so this removes it instead of keeping it next to `Listen<T>`. Code compiled against it must be recompiled. Two kinds of hand-written calls no longer compile: a `null` literal, from which C# can't infer `T`, and a ref struct that converts to an object, which can't be a type argument here. Generated subscribers pass neither.  **Left:** time per update for a binding that observes the property being replaced. Each bar is the best of 9 runs of 2,000,000 updates in each of 11 interleaved main/PR process pairs. Paths through objects that notify are unchanged. Paths through a struct are 9–13% faster, and their updates no longer allocate. **Right:** bytes allocated per operation by the new `TypedBindingStructPathBenchmarker`. It uses a source-generated `Bounds.Width` binding to a `double` property. The 24 B left per update is the boxed `double` that the target stores. <details> <summary>All numbers</summary> **Interleaved probe.** This is a console app that isn't part of this PR. It binds a `string` property through subscribers with the generated shape, compiled against each build, and replaces the observed property in a loop. Each row is 11 interleaved process pairs, best of 9 runs of 2,000,000 updates. | Path | main best (median) | PR best (median) | Change (best) | main B per update | PR B per update | | --- | ---: | ---: | ---: | ---: | ---: | | `Name` | 22.17 ns (22.48) | 22.01 ns (22.37) | −0.7% | 0 | 0 | | `Child.Name` | 25.69 ns (26.16) | 25.53 ns (26.29) | −0.6% | 0 | 0 | | `Child.Child.Name` | 27.40 ns (28.10) | 27.24 ns (28.10) | −0.6% | 0 | 0 | | `Point.Name`, through a struct | 28.48 ns (29.86) | 24.67 ns (25.71) | −13.4% | 32 | 0 | | `Holder.Point.Name`, through a struct | 31.20 ns (33.70) | 28.31 ns (29.36) | −9.3% | 32 | 0 | | `Bounds.Width.ToString()`, through `Rect` | 51.80 ns (52.84) | 46.29 ns (49.18) | −10.6% | 80 | 32 | **BenchmarkDotNet, `TypedBindingStructPathBenchmarker`.** Paired runs ordered main, PR, PR, main. "main" includes the new benchmark. Values are per iteration, and each operation runs 100 iterations. | Benchmark | main min (median) | PR min (median) | Change (min) | main B | PR B | | --- | ---: | ---: | ---: | ---: | ---: | | `StructUpdate` | 40.3 ns (43.3) | 35.4 ns (37.2) | −12.1% | 72 | 24 | | `ContextSwap` | 108.4 ns (123.1) | 103.1 ns (143.8) | −4.9% | 112 | 64 | | `CreateApplyAndRemove` | 383.9 ns (467.6) | 342.0 ns (419.0) | −10.9% | 880 | 832 | The same runs included the 44 cases of `TypedBindingDepthBenchmarker` and `TypedBindingIntermediateBenchmarker`, both generated and legacy bindings, as a control. Their allocations are identical on both sides. The host was heavily loaded during the runs, with a load average of about 40–50. BenchmarkDotNet times moved by up to ±20% even in the legacy cases, whose code this PR doesn't change. So these times, including the `ContextSwap` median, are only indicative. The interleaved probe above is the timing evidence. </details> #### Changes - `TypedBindingListeners.cs` replaces `Listen(object?)` with `TypedBindingListeners.Listen<T>`, and adds `TypedBindingSubscriptions.ListenToNothing` and `Listener.IsDetached`. - `PublicAPI.Unshipped.txt` replaces `Listen(object?)` with `Listen<T>` for all six target frameworks. - A new test in `TypedBindingCompatibilityTests`, `ValueThatCannotNotifyRemovesHandlerAtItsPosition`, checks that a struct that can't notify, reported where an object that notifies was, removes that object's handler. - New benchmark `TypedBindingStructPathBenchmarker`: updates through `Rect`, binding context changes, and creating, applying and removing such a binding. It's the first commit, so it can be run on main. #### Validation These were run on macOS arm64 with the pinned SDK 12.0.100-alpha.1.26523.103. Each test project was built first with `dotnet build <project> -c Debug -p:MauiPlatforms= -p:IncludePreviousTfms=false -p:PublicApiType=Validate`. Xaml.UnitTests also needs the build tasks, from `dotnet build Microsoft.Maui.BuildTasks.slnf -p:MauiPlatforms= -p:IncludePreviousTfms=false`. The tests ran again at 2481e06, after `Listen(object?)` was removed. | Command | Result | | --- | --- | | `dotnet test --project src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj -c Debug --no-build` | 7,685 passed, 30 skipped, 31 failed. The new test passes. The same 31 async leak tests fail on main without this change. They have failed since #40824, whose PR build [1704502](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1704502) failed them on all four unit-test legs. | | `dotnet test --project src/Controls/tests/BindingSourceGen.UnitTests/Controls.BindingSourceGen.UnitTests.csproj -c Debug --no-build`, with #40844 applied | 157 passed. Without #40844, this project doesn't build on main (xUnit1051). | | `dotnet test --project src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj -c Debug --no-build` | 934 passed, 71 skipped | | `dotnet test --project src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj -c Debug --no-build` | 2,341 passed, 8 skipped | | `Core.Benchmarks.dll --filter '*TypedBindingStructPathBenchmarker*' '*TypedBindingDepthBenchmarker*' '*TypedBindingIntermediateBenchmarker*' --iterationCount 10 --iterationTime 120 --warmupCount 3 --launchCount 1`, in Release, paired as above | See "All numbers" above. These ran at 4de66a2, before `Listen(object?)` was removed. The measured subscribers called `Listen<T>` there too. | Until #40844 merges, the unit-test legs of this PR's CI will fail on `BindingSourceGen.UnitTests`. They'll also fail on the 31 leak tests from #40824 until those are fixed. ### Issues Fixed <!-- Please make sure that there is a bug logged for the issue being fixed. The bug should describe the problem and how to reproduce it. --> No issue is filed. This is a follow-up to #40819. ### Let AI finish this PR - [ ] **Let the MAUI agent address review feedback and fix remaining issues on this PR.** Maintainers still decide whether it is merged. For PRs from forks, keep "Allow edits by maintainers" on so the agent can push to your branch; otherwise it opens a follow-up PR that keeps your commits. <!-- Verify the target branch follows the release workflow in docs/ReleaseBranchWorkflow.md. Infrastructure and documentation changes should target the branch where they apply. --> --------- Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>


Agent assessment
Self-reported assessment, not an independent review.
Assessed revision:
8dc4c8067df4d45478b93d52eab85aab0febce56↑ MSBuild evaluation confirmed net12 enables
runtime-async=on, net11/netstandard remain unchanged, and an explicitruntime-async=offis preserved.↑ The Android sample-content benchmark installed and launched with the feature; APK size fell 0.48%.
↓ The .NET 12 upstream default-on rollout is still open, and broad physical-device/CI runtime validation remains pending.
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!
Target Branch
mainnet11, for reviewFor .NET 11 fixes, only a maintainer retargets the approved PR to the active
inflight lane and merges it after CI validates that final base. Do not merge
individual fixes directly into
net11; agents must not retarget or merge.Description of Change
Enables Runtime Async V2 for the current .NET 12 target in both places MAUI compilation is configured:
Directory.Build.targets.BundledVersions.targets.The setting is idempotent and scoped to net12. It leaves net11 and .NET Standard assets unchanged and does not replace an explicit
runtime-asyncselection, so a project can opt out withFeatures=runtime-async=off.What Runtime Async changes
Today, C# normally implements an
asyncmethod by generating a state-machine type andMoveNextmethod. Runtime Async instead marks eligible methods with the runtime async metadata contract and lets the runtime/JIT track suspension and resumption. The draft ECMA-335 specification, originally introduced by dotnet/runtime#104063, documents theMethodImplOptions.Asyncmethod contract andAsyncHelpersawait operations.The practical benefits are narrower, cleaner live stack traces/debugger views, fewer compiler-generated async state-machine types, and additional JIT opportunities such as directly calling runtime-async variants and avoiding intermediate task/continuation work. The .NET 11 performance deep dive covers those optimizations and also notes the current boundaries: Runtime Async supports
Task,Task<T>,ValueTask, andValueTask<T>, whileasync void, async iterators, and arbitrary custom task-like builders continue to use the traditional transformation.Runtime Async supports both ReadyToRun and NativeAOT in .NET 11. The corresponding upstream R2R and NativeAOT tracking issues are dotnet/runtime#115098 and dotnet/runtime#124101; the latter is complete and the former is closed with its implementation work substantially complete.
.NET rollout and why .NET 12
The upstream Runtime Async tracking issue is now on the .NET 12.0 milestone. Its current status distinguishes the two stages of rollout:
EnablePreviewFeatures; however, application code still opts in withruntime-async=on. The runtime libraries/shared framework are already compiled with it. See the Microsoft Learn runtime guide and .NET 11 overview.There is a concrete upstream rollout PR: dotnet/runtime#138389, “Opt-in into runtime async for all .NET 12+ projects”. As of 2026-11-29 it is open, with approvals but not yet merged; a reviewer notes that this repository-level opt-in should be removable once the .NET SDK defaults it on. The PR also exposed a crossgen2 issue now being addressed in dotnet/runtime#138405.
Earlier rollout work already auto-enabled Runtime Async for supported shared-framework net11+ sources and removed the runtime configuration knob in dotnet/runtime#125406, with a corresponding .NET 11 preview backport in dotnet/runtime#126343. This MAUI PR therefore targets the same transition for MAUI's .NET 12 source and packages without changing net11 or netstandard compatibility.
Android sample-content benchmark
The generated
maui --sample-contentapp was compared in Release forandroid-arm64with CoreCLR, ReadyToRun, andTrimMode=partial:The package reduction came entirely from
libassembly-store.so. Startup used 20am start -W -Slaunches per variant across two speed-compiled, warmed blocks on an ARM64 API 35 emulator. IQRs overlapped (710.5–819.25 ms vs. 747.75–825.5 ms) and paired block deltas had opposite signs, so there was no demonstrated startup improvement or regression.Validation
./.dotnet/dotnet msbuild eng/Microsoft.Maui.Packages-mac.slnf -restore '-t:Rebuild;Pack' -p:Configuration=Release -p:Pack=true -m -v:minimal— passed at the assessed revision../.dotnet/dotnet build src/Core/src/Core.csproj -c Release -f net12.0-android37.0 -t:Rebuild --no-restore -v:minimal— passed.Featuresevaluation — net12 defaults toruntime-async=on,runtime-async=offis preserved, and net11/netstandard remain unchanged.Issues Fixed
N/A — no issue was provided.
Let AI finish this PR