Repository navigation
feat: optionally marshal off-thread collection and item changes to the UI thread (#410) - #520
Open
michaelstonis wants to merge 2 commits into
Open
michaelstonis wants to merge 2 commits into
michaelstonis wants to merge 2 commits into
Conversation
| 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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #410.
Changes
Adds an opt-in mode in which
KumikoSourceaccepts collection changes and itemPropertyChangedraised 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.KumikoCrossThreadChangesenum:Reject(the default) andMarshal.KumikoSource.CrossThreadChanges,KumikoSource.CrossThreadUpdateInterval(100 ms by default; a negative value throws) andKumikoSource.CollectionSyncRoot.KumikoDataGrid:CrossThreadChanges,CrossThreadUpdateIntervalandCollectionSyncRootbindable properties, plus their...Propertyfields. The interval property rejects negative values throughvalidateValue.KumikoDataGrid: the same three as dependency properties, plus their...Propertyfields.All of these are recorded in each project's
PublicAPI.Unshipped.txt.How it works (
src/KumikoUI.Core/Models/KumikoSource.CrossThread.cs)if (IsForeignThreadChange()) return;. InRejectmode this helper throwsWrongThreadMessageexactly as before. InMarshalmode it only sets a pending flag withInterlocked. If no update is pending yet, it schedules one: aTask.Delayon an internalTimeProvider, then a post to the owner context. The handler then returns without touching any source state, so subscriptions,_trackedItemsand the view are never changed off-thread.ItemBuffer, holdingCollectionSyncRootwhen it is set. It re-subscribes itemPropertyChangedfrom 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 oneViewChanged(Rebuild). A large source rebuilds through the existing background path.Marshalmode views are always built over a copy (the existingItemsAreCopypath;RebuildCorecopies whenever the mode isMarshal). 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.CollectionSyncRootin this mode:RemoveItems,ReorderRowand the item subscription after aReset.SynchronizationContextthe update goes toHostContext, an internalKumikoDispatcherContextthat each grid supplies (MAUIIDispatcher.Dispatch, UnoDispatcherQueue.TryEnqueue). With neither, pending changes apply on the nextRefresh().HostContextis used only for these updates, so background rebuilds on a thread without a context stay synchronous, as before.Marshalrebuilds the view over a copy. Switching back toRejectkeeps an update that is already pending.SetItems,AttachandDisposedrop a pending update, and an update that arrives afterDetachorDisposedoes nothing.Composition with #362. #362 adds
IBindingList.ListChangedhandling in a newKumikoSource.BindingList.cs. Its handler needs to start withif (IsForeignThreadChange()) return;, the same guard the collection and item handlers use, instead ofif (!CheckAccess()) RejectForeignThreadChange();. With that one line, aListChangedraised off-thread is rejected or marshaled like the other notifications. The marshaled update re-subscribes only itemPropertyChanged; list-level subscriptions are untouched. Item subscription is factored asSubscribeToItemPropertyChanged(IList), which locks inMarshalmode.Hosts. Both hosts got
KumikoDataGrid.CrossThread.cswith the three properties andInitializeCrossThread(), called from the constructor. The comment inOnBoundItemsCollectionChangednow explains that inMarshalmode 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 withCrossThreadChanges="Marshal",CollectionSyncRootset 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 (
decimaland other values wider than a machine word), full rebuilds, the fallback order (context, then dispatcher, thenRefresh) and whyRejectstays 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 toViewPipelineTests.cs), 14 tests:Rejectis unchanged (throws, then resyncs).Marshalaccepts adds, removes and property changes from a worker without throwing.ViewChangedper interval, and nothing applies 1 tick before the interval.RowCount,GetItem,GetCellValue,ItemCount,GetUniqueColumnValues).CollectionSyncRootis honored: a guarded list counts UI-thread element reads made without the lock and finds none, through updates, reads, selection,RemoveItemsandReorderRow.Refreshapplies the changes; with onlyHostContext, the dispatcher carries the update.DetachorDisposedoes nothing.All of them are deterministic: they use
TestUiThreadplus a newManualTimeProvidertest 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.txtupdated for Core, Maui and Uno.eng/update-public-api.sh Coreemptied 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
Rebuildnotification, 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 inMarshalmode, 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 twoUno0001warnings 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 withNU1605, aMicrosoft.Maui.Controlspackage downgrade between the sample and SkiaSharp.Views.Maui.Controls. That comes from package versions, not from this change, which only adds aCompileitem. With-p:NoWarn=NU1605it builds without errors.dotnet run --project eng/DocsSnippets -c Release, thendotnet build tests/KumikoUI.Docs.Snippets.Uno -f net10.0-desktop -c Releaseanddotnet 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.