Skip to content

feat: optionally marshal off-thread collection and item changes to the UI thread (#410) - #520

Open
michaelstonis wants to merge 2 commits into
mainfrom
feat/410-cross-thread-marshal
Open

michaelstonis wants to merge 2 commits into
mainfrom
feat/410-cross-thread-marshal

Conversation

@michaelstonis

Copy link
Copy Markdown
Contributor

Closes #410.

Changes

Adds an opt-in mode in which KumikoSource accepts collection changes and item PropertyChanged raised on a background thread. The source applies them on the UI thread at a throttled interval. The default, Reject, keeps the 1.0 behavior: such a change throws.

Public API (additions only)

  • KumikoUI.Core.Models.KumikoCrossThreadChanges enum: Reject (the default) and Marshal.
  • KumikoSource.CrossThreadChanges, KumikoSource.CrossThreadUpdateInterval (100 ms by default; a negative value throws) and KumikoSource.CollectionSyncRoot.
  • MAUI KumikoDataGrid: CrossThreadChanges, CrossThreadUpdateInterval and CollectionSyncRoot bindable properties, plus their ...Property fields. The interval property rejects negative values through validateValue.
  • Uno KumikoDataGrid: the same three as dependency properties, plus their ...Property fields.

All of these are recorded in each project's PublicAPI.Unshipped.txt.

How it works (src/KumikoUI.Core/Models/KumikoSource.CrossThread.cs)

  • Every change-notification handler now starts with if (IsForeignThreadChange()) return;. In Reject mode this helper throws WrongThreadMessage exactly as before. In Marshal mode it only sets a pending flag with Interlocked. If no update is pending yet, it schedules one: a Task.Delay on an internal TimeProvider, then a post to the owner context. The handler then returns without touching any source state, so subscriptions, _trackedItems and the view are never changed off-thread.
  • On the UI thread the update clears the flag and copies the items into an ItemBuffer, holding CollectionSyncRoot when it is set. It re-subscribes item PropertyChanged from that copy, bumps the collection version, invalidates the cell text and row layout caches, and requests one rebuild over that same copy. A burst of changes in one interval becomes one update, one rebuild and one ViewChanged (Rebuild). A large source rebuilds through the existing background path.
  • In Marshal mode views are always built over a copy (the existing ItemsAreCopy path; RebuildCore copies whenever the mode is Marshal). The live-collection reads outside the view now read the view's copy in this mode: ItemCount, the filter value list (GetUniqueColumnValues) and an export of all items. So the renderer, hit tester and selection read only the copy, which is done in the data layer: no renderer, input-controller or hit-tester file was changed.
  • The grid's own writes to the collection hold CollectionSyncRoot in this mode: RemoveItems, ReorderRow and the item subscription after a Reset.
  • UI-thread changes keep their incremental path, except while a cross-thread update is pending. Then the collection holds more than the notification says, so the change takes the rebuild path instead.
  • Without a lock, a copy that a concurrent change breaks is retried. If it still fails, the current view stays and the next update copies again, so a torn copy never throws on the UI thread.
  • With no SynchronizationContext the update goes to HostContext, an internal KumikoDispatcherContext that each grid supplies (MAUI IDispatcher.Dispatch, Uno DispatcherQueue.TryEnqueue). With neither, pending changes apply on the next Refresh(). HostContext is used only for these updates, so background rebuilds on a thread without a context stay synchronous, as before.
  • Switching to Marshal rebuilds the view over a copy. Switching back to Reject keeps an update that is already pending. SetItems, Attach and Dispose drop a pending update, and an update that arrives after Detach or Dispose does nothing.

Composition with #362. #362 adds IBindingList.ListChanged handling in a new KumikoSource.BindingList.cs. Its handler needs to start with if (IsForeignThreadChange()) return;, the same guard the collection and item handlers use, instead of if (!CheckAccess()) RejectForeignThreadChange();. With that one line, a ListChanged raised off-thread is rejected or marshaled like the other notifications. The marshaled update re-subscribes only item PropertyChanged; list-level subscriptions are untouched. Item subscription is factored as SubscribeToItemPropertyChanged(IList), which locks in Marshal mode.

Hosts. Both hosts got KumikoDataGrid.CrossThread.cs with the three properties and InitializeCrossThread(), called from the constructor. The comment in OnBoundItemsCollectionChanged now explains that in Marshal mode the handler can run off-thread. It already dispatched its repaint and auto-column work.

Sample. The Large Data page of both apps has a "Background feed" switch. It uses a new shared samples/Shared/BackgroundFeed.cs. Every 20 ms, on a thread-pool thread holding the feed's lock, it edits 10 rows (double properties only), adds a row and removes the oldest. The grid runs with CrossThreadChanges="Marshal", CollectionSyncRoot set to the feed's lock and a 100 ms interval. The feed stops on load, on clear and when the page goes away.

Docs. The README "Threading" section has a new part on accepting changes from a background feed. It covers the snippet, the lock requirement, torn values (decimal and other values wider than a machine word), full rebuilds, the fallback order (context, then dispatcher, then Refresh) and why Reject stays the default. The performance tips line, the samples README row and a CHANGELOG entry under Unreleased / Added are also updated.

Acceptance criteria

  • Behavior tests in tests/KumikoUI.Core.Tests (CrossThreadChangesTests.cs, next to ViewPipelineTests.cs), 14 tests:

    • Reject is unchanged (throws, then resyncs).
    • Marshal accepts adds, removes and property changes from a worker without throwing.
    • A burst becomes exactly one update, one rebuild and one ViewChanged per interval, and nothing applies 1 tick before the interval.
    • Between updates every read answers from the copy (RowCount, GetItem, GetCellValue, ItemCount, GetUniqueColumnValues).
    • CollectionSyncRoot is honored: a guarded list counts UI-thread element reads made without the lock and finds none, through updates, reads, selection, RemoveItems and ReorderRow.
    • Selection and the current cell follow their items.
    • Background rebuild of a large source.
    • Switching modes at runtime.
    • Zero interval.
    • Without a context, Refresh applies the changes; with only HostContext, the dispatcher carries the update.
    • An update after Detach or Dispose does nothing.

    All of them are deterministic: they use TestUiThread plus a new ManualTimeProvider test clock, with no sleeps.

  • Works on MAUI and Uno: the properties exist on both hosts, and each grid supplies its dispatcher as the fallback post target. MAUI host tests check forwarding, validation and a marshaled background add. Uno has no grid-construction test harness, so the Uno side is covered by its build and the Core tests. No on-device run was made.

  • Sample app: background feed demo on the Large Data page, MAUI and Uno.

  • XML docs on every new public member.

  • PublicAPI.Unshipped.txt updated for Core, Maui and Uno. eng/update-public-api.sh Core emptied the file on this machine (the code-fix step did not write the surface back), so the entries were added by hand in the files' order. The builds pass with no RS0016/RS0017.

  • README "Threading" section updated, including the lock requirement and torn values.

  • CHANGELOG entry under Unreleased.

  • Keyboard and screen-reader behavior unchanged across marshaled rebuilds. A marshaled update raises one ordinary Rebuild notification, which the hosts already handle; there is no new announcement path. The current cell and selection follow their items (tested).

  • No allocations added to the per-frame render path. The render loop is unchanged. ItemCount, read every frame for the empty view, reads the view's copy instead of the collection in Marshal mode, with the same cost and no allocation.

Verification

  • dotnet build src/KumikoUI.Core: succeeded, no warnings.
  • dotnet build src/KumikoUI.Maui -f net10.0-maccatalyst: succeeded, no warnings.
  • dotnet build src/KumikoUI.Uno -f net10.0-desktop: succeeded. The only warnings are the two Uno0001 warnings that were already there (KumikoDataGrid.Editing.cs, KumikoDataGrid.Input.cs).
  • dotnet test tests/KumikoUI.Core.Tests: 4375 passed, 5 skipped, 0 failed. The threading tests (CrossThreadChangesTests, ViewPipelineTests, BackgroundRebuildTests) were also run 8 times in a row, all passing.
  • dotnet test tests/KumikoUI.Maui.Tests: 451 passed.
  • dotnet test tests/KumikoUI.Uno.Tests: 321 passed.
  • dotnet build samples/SampleApp.Uno -f net10.0-desktop: succeeded.
  • dotnet build samples/SampleApp.Maui -f net10.0-maccatalyst: fails at restore with NU1605, a Microsoft.Maui.Controls package downgrade between the sample and SkiaSharp.Views.Maui.Controls. That comes from package versions, not from this change, which only adds a Compile item. With -p:NoWarn=NU1605 it builds without errors.
  • dotnet run --project eng/DocsSnippets -c Release, then dotnet build tests/KumikoUI.Docs.Snippets.Uno -f net10.0-desktop -c Release and dotnet build tests/KumikoUI.Docs.Snippets.Maui -f net10.0-maccatalyst -c Release: both succeeded, so the new README snippet compiles.
  • dotnet run --project eng/TypeNameCheck -c Release -- src/KumikoUI.Core/bin/Debug/net10.0/KumikoUI.Core.dll: no collisions.
  • dotnet run --project eng/DocsIdentifiers -c Release: 0 problems.

public void Start(ObservableCollection<T> items, TimeSpan period, Action<ObservableCollection<T>, Random> tick)
{
if (_cts != null) return;
var cts = _cts = new CancellationTokenSource();

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

Data: optionally marshal off-thread collection and item changes to the UI thread

2 participants