0
votes

I have list that is bound to a view when it loads which works fine. I also have a timer that calls a service to check for any new items to add to the list. The problem occurs when I try and add new items to the list I get a error that it needs to be done on the UI thread.

I am attempting to add the items to an ObservableCollection as Below:

private ObservableCollection<ChatMessageViewModel> _items;

public MyViewModel(IMvxMessenger messenger, IMyService myService) : base (messenger)
    {
        _myService = myService;
        _timer = new Timer(GetLatestItems,null, 1000,10000);
    }


public async void GetLatestItems()
    {
       var newItems = await _myService.GetNewMessages();
        if (newItems != null && newItems.Count > 0)
        {
            foreach (var item in newItems)
            {
                Items.Add(item);
            }
        }
    }
1

1 Answers

3
votes

ObservableCollection/INotifyCollectionChanged must be used synchronously - so you must use it on the UI thread.

Timer uses a ThreadPool thread.

To marshall the call back onto the UI, try something like:

public MyViewModel(IMvxMessenger messenger, IMyService myService) : base (messenger)
{
    _myService = myService;
    _timer = new Timer(GetLatestItems,null, 1000,10000);
}

public async void GetLatestItems()
{
   var newItems = await _myService.GetNewMessages();
   InvokeOnMainThread(() => {
    if (newItems != null && newItems.Count > 0)
    {
        foreach (var item in newItems)
        {
            Items.Add(item);
        }
    }
 });