-1

Hi I want to use the ObservableCollection (AddRange) in async Task but i get NotSupportedException

private ObservableCollection<CoronavirusCountry> _data = new ObservableCollection<CoronavirusCountry>();
        public ObservableCollection<CoronavirusCountry> data
        {
            get => _data;
            set => SetProperty(ref _data, value);
        }

Task.Run(async()=>{
   APIService service = new APIService();
            data.AddRange(await service.GetTopCases());
            Status = "Updated " + DateTime.Now;

});
Atena
  • 109
  • 2
  • 9
  • 1
    Does this answer your question? [How do I update an ObservableCollection via a worker thread?](https://stackoverflow.com/questions/2091988/how-do-i-update-an-observablecollection-via-a-worker-thread) – Peter Duniho Jul 19 '20 at 06:47
  • @PeterDuniho thank you, How can I use this extension with addrange? – Atena Jul 19 '20 at 07:17

1 Answers1

1

Not sure which AddRange method you are referring to, because ObservableCollection doesn't have that out of the box.

Anyway - assuming you wrote an extension method - it has to be called in the UI thread, so running a Task doesn't make sense.

The awaitable method shown below should be sufficient. It would await the asynchronous service call, and update the collection in the main thread.

public async Task UpdateData()
{
    var service = new APIService();
    var newData = await service.GetTopCases();

    Data.AddRange(newData); // use proper naming!

    Status = "Updated " + DateTime.Now;
}

In order to call and await the above method, you could have an async Loaded event handler like this:

public MainWindow()
{
    InitializeComponent();

    viewModel = new ViewModel();

    Loaded += async (s, e) => await viewModel.UpdateData();
}
Clemens
  • 123,504
  • 12
  • 155
  • 268
  • thank you but i need to call this method in ctor, and i heard that if i call `UpdateData().Wait() ` Causes deadblock That's why I want to execute the code within the task – Atena Jul 19 '20 at 07:16
  • You can't call an awaitable method in a constructor - and the Task you were creating must also be awaited. If you are referring to the constructor of a UI element, e.g. a Window or UserControl, call it in an async Loaded event handler. – Clemens Jul 19 '20 at 07:17
  • my ctor is in viewmodel (prism mvvm) – Atena Jul 19 '20 at 07:20