Advertisement
Advanced .NET MAUI, Concurrency & Threading

How do you safely update collections bound to the UI from background threads?

Short answer

Marshal collection mutations to the UI thread, since CollectionView observes changes on the UI thread. Compute/fetch data in the background, then add items via MainThread.BeginInvokeOnMainThread, or gather results and assign once.

Save .NET MAUI mock interview
Advertisement
AModel answer
Marshal collection mutations to the UI thread, since CollectionView observes changes on the UI thread. Compute/fetch data in the background, then add items via MainThread.BeginInvokeOnMainThread, or gather results and assign once. Some toolkit collections offer thread-safe patterns, but explicit marshaling is safest.
var page = await _api.GetPageAsync();
MainThread.BeginInvokeOnMainThread(() =>
{
    foreach (var item in page) Items.Add(item);
});
Real-world example
Paged results fetched off-thread are appended to the bound ObservableCollection on the UI thread to avoid exceptions.
Likely follow-ups
  • Why marshal collection changes? | Can you assign the whole collection at once?
Related topics