简体   繁体   English

异步任务中的 ObservableCollection AddRange

[英]ObservableCollection AddRange in async Task

Hi I want to use the ObservableCollection (AddRange) in async Task but i get NotSupportedException您好我想在异步任务中使用 ObservableCollection (AddRange) 但我得到 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.不确定您指的是哪个AddRange方法,因为 ObservableCollection 没有开箱即用的方法。

Anyway - assuming you wrote an extension method - it has to be called in the UI thread, so running a Task doesn't make sense.不管怎样——假设你写了一个扩展方法——它必须在 UI 线程中调用,所以运行一个 Task 没有意义。

The awaitable method shown below should be sufficient.下面显示的 awaitable 方法应该足够了。 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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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