GuidesPoll a remote source
Poll a remote source
Poll a source that offers nothing to subscribe to, report each refresh as changed or unchanged, and keep polling through failures.
A REST API or a database has no change token to subscribe to, so a polling source asks on a timer and signals when the answer differs. How the timer, the refresh and failures behave is on periodic polling.
Create the polling source
Section titled “Create the polling source”Give the factory the state your refresh needs, such as an API client, the collection to serve until the first refresh, the interval and the refresh callback. The first refresh follows the first tick, so the initial collection is what readers see until then. Dispose the source when you are done with it.
await using var dataSource = factory.CreatePeriodicPolling<string, UserDirectory>( state: directory, initialCollection: [], refreshInterval: refreshInterval, refreshCollectionAsync: async (source, current, ct) => { var users = await source.GetUsersAsync(ct); return users is null || users.SequenceEqual(current) ? RefreshCollectionResultFactory.Unchanged<string>() : RefreshCollectionResultFactory.Changed(users); }, handleExceptionAsync: (ex, ct) => { Console.Error.WriteLine($"Failed to refresh users: {ex.SourceException.Message}"); return ValueTask.CompletedTask; });The sample serves an empty collection and asks a UserDirectory, a stand-in for a remote service, on each tick. Use an interval that suits the remote service.
Report changed or unchanged
Section titled “Report changed or unchanged”The refresh callback gets the state, the collection last stored and a cancellation token, and it returns a result. Unchanged<string>() keeps the collection and signals nothing. Changed(users) stores the new collection and signals, so a provider over the source rebuilds.
The source never compares the new collection with the old one. The sample returns Unchanged when the answer is null or equal to current, and your code decides what equal means, such as an ETag or a version.
Handle failures
Section titled “Handle failures”An exception from the refresh goes to the handler, which here writes the message to Console.Error. A handler that returns keeps the collection and polling goes on, so the next tick tries again. See failures for what ends polling.
Test code that polls
Section titled “Test code that polls”Register a FakeTimeProvider, from the Microsoft.Extensions.TimeProvider.Testing package, as the container’s TimeProvider before you call AddLiveCollections(). AddLiveCollections() registers TimeProvider.System only when no TimeProvider is registered, so every polling source the factory creates then ticks on your fake clock.
var time = new FakeTimeProvider(new DateTimeOffset(2025, 1, 1, 0, 0, 0, TimeSpan.Zero));var services = new ServiceCollection();services.AddSingleton<TimeProvider>(time);services.AddLiveCollections();await using var serviceProvider = services.BuildServiceProvider();var factory = serviceProvider.GetRequiredService<ICollectionDataSourceFactory>();
var refreshInterval = TimeSpan.FromMinutes(5);var refreshed = RefreshCollectionResultFactory.Changed<string>(["ada"]);await using var dataSource = factory.CreatePeriodicPolling<string, object?>( state: null, initialCollection: [], refreshInterval: refreshInterval, refreshCollectionAsync: (state, current, ct) => ValueTask.FromResult(refreshed));
var changed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);using var subscription = ChangeToken.OnChange(dataSource.GetChangeToken, () => changed.TrySetResult());
var timeout = TimeSpan.FromSeconds(5);time.Advance(refreshInterval);await changed.Task.WaitAsync(timeout);time.Advance(refreshInterval) fires one tick, and the sample waits for the change token instead of calling Task.Delay. Advance one interval for each refresh you wait for, because ticks the source has not taken yet collapse into one. Without a container, pass the clock to new DefaultCollectionDataSourceFactory(time), or to the timeProvider parameter of the PeriodicPollingCollectionDataSource constructor.
Pitfalls
Section titled “Pitfalls”-
Passing no exception handler.
- You write
CreatePeriodicPollingwithouthandleExceptionAsync. - What happens: the default rethrows, so the first failure ends polling. Nobody sees an exception or a signal, and the collection stays as last stored.
- Write instead: pass a handler that logs and returns.
- You write
-
Returning Changed with the same items.
- You write
Changed(users)after every refresh, whether or not the data differs. - What happens: the source does not compare, so each refresh signals and each signal rebuilds the provider’s collection.
- Write instead: return
Unchanged<TItem>()when the data is the same.
- You write
-
Ignoring the cancellation token.
- You write a refresh that calls the remote service without passing the token on.
- What happens:
DisposeAsynccancels the token and awaits the polling task, so disposal waits for the refresh to finish. - Write instead: pass the token to every call the refresh makes.
-
Waiting in real time in a test.
- You write a short interval and
Task.Delayuntil a refresh has run. - What happens: the test is slow, and fails when the machine is busy.
- Write instead: register a
FakeTimeProviderand callAdvance.
- You write a short interval and
-
Not disposing the source.
- You write a polling source that nothing disposes.
- What happens: the timer and the polling task keep running and keep calling the remote service.
- Write instead: dispose it with
await using, or let a provider that owns it dispose it, which is the default for a single source.