Suppress ExecutionContext flow for render scheduling by Shirasagi0012 · Pull Request #21273 · AvaloniaUI/Avalonia (original) (raw)
What does the pull request do?
Prevents Avalonia's internal render scheduling from inappropriately capturing the ambient ExecutionContext.
After PR #19163, dispatcher operations correctly capture ExecutionContext, which allows AsyncLocal values to flow through user-dispatched UI work. However, MediaContext also schedules Avalonia-internal render-loop work through the dispatcher. That internal scheduling should not preserve the ambient ExecutionContext, as this causes AsyncLocal values to flow into the next render loop run.
What is the current behavior?
When a render pass or layout invalidation schedules the next render operation while an AsyncLocal value is active, the dispatcher captures that value for Avalonia's internal render operation.
This can cause diagnostics based on ActivitySource / Activity.Current to incorrectly parent future render-loop activities, making the activity tree grow longer across frames. You can observe this issue with an OTel exporter and a span viewer (e.g. using .NET Aspire dashboard), and you can find that all spans after a certain point end up sharing the same incorrect span root.
I ran into this issue while heavily instrumenting the render loop and compositor for profiling. It makes diagnostics quite difficult because it causes spans to be associated incorrectly.
What is the updated/expected behavior with this PR?
Avalonia suppresses ExecutionContext flow while scheduling internal render-loop dispatcher operations, so ambient AsyncLocal values do not flow into the next render pass.
User-created dispatcher operations still capture ExecutionContext normally.
Added regression coverage for render scheduling with ambient AsyncLocal state and for the case where execution-context flow is already suppressed.
How was the solution implemented (if it's not obvious)?
MediaContext.ScheduleRender now wraps creation/enqueueing of its internal dispatcher operations in ExecutionContext.SuppressFlow() scope.
Checklist
- Added unit tests (if possible)?
- Added XML documentation to any related classes?
- Consider submitting a PR to https://github.com/AvaloniaUI/avalonia-docs with user documentation