简体   繁体   中英

ObservableCollection AddRange in async Task

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;

});

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM