WPF update binding in a background thread

后端 未结 5 1278
情话喂你
情话喂你 2020-12-25 07:52

I have a control that has its data bound to a standard ObservableCollection, and I have a background task that calls a service to get more data.

I want

5条回答
  •  醉梦人生
    2020-12-25 08:35

    If i understand correctly, you already use a BackgroundWorker to retrieve the data, and that simply assigning this data to the ObservableCollection is locking up the UI.

    One way to avoid locking up the UI is to assign the data to the ObservableCollection in smaller chunks by queuing multiple dispatcher methods. Between each method call, UI events can be handled.

    the following would add one item on at a time, that's a bit extreme, but it illustrates the concept.

    void UpdateItems()
    {
        //retrievedItems is the data you received from the service
        foreach(object item in retrievedItems)
            Dispatcher.BeginInvoke(DispatcherPriority.Background, new ParameterizedThreadStart(AddItem), item);    
    }
    
    void AddItem(object item)
    {
        observableCollection.Add(item);
    }
    

提交回复
热议问题