Skip to content

ConceptsHow a provider rebuilds

How a provider rebuilds

How a provider subscribes to change tokens, rebuilds its collection in full, and keeps reads free of locks.

A provider turns its data source’s items into one collection and keeps that collection current. This page follows one change from the signal to the rebuilt collection. To see it run, start with the quick start.

A source reports a change through GetChangeToken(), which returns an IChangeToken from Microsoft.Extensions.Primitives. A token signals once. After it signals, the caller asks for a fresh one. ChangeToken.OnChange does that for you: it subscribes again after each signal.

A provider subscribes to its change-token producers on the first read of Collection or the first call of GetChangeToken(). It never subscribes in the constructor, so a provider that is never read pays for neither the subscription nor the build.

The producers are the data source and any extra producers passed to the provider’s constructor. With several sources, an internal composite aggregates them.

When any producer signals, the provider replaces its own token. If its collection is already built, it calls CreateCollection with the data source’s whole Collection. It never applies a diff, so each signal costs one full CreateCollection, and a burst of N edits to an observable source makes N signals and N rebuilds.

A collection that was never read is not rebuilt on a signal. It is built on its first read.

The provider cancels the old token after the rebuild, and after it has released its lock. A callback registered on that token therefore reads the rebuilt collection, and it may read Collection without waiting on the provider.

Collection and GetChangeToken() return a cached value and take no lock. Only the first call takes the provider’s lock, and it initializes once under it, so many threads reading an unbuilt provider cause one CreateCollection call.

Initialization and rebuilds run one at a time under that lock, on the thread that signalled. That thread is the one that edited an observable collection, or the polling task’s thread. Two rules follow:

  • A slow CreateCollection delays the code that changed the source. Keep it short.
  • A CreateCollection that waits on another thread reading the same unbuilt provider can deadlock.

The provider replaces its reference to the collection whole. A reader gets the previous collection or the rebuilt one, never a partial one. The provider guarantees that swap, not the contents: a collection factory that returns the items as given hands out the source’s live view, so copy them when readers need a snapshot.

After DisposeAsync, Collection and GetChangeToken() throw ObjectDisposedException. A signal that arrives late does nothing.