WPF update binding in a background thread

后端 未结 5 1444
情话喂你
情话喂你 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:25

    ObservableCollection will raise CollectionChanged events that will force UI to rebind data, measure, arrange and redraw. This might take a lot of time if you have many updates coming.

    It is possible to make user think that UI is alive by splitting the job in small packages. Use Dispatcher from UI thread (any control has reference to it) to schedule collection update actions with 10-100 items (determine number by experiment, these just to support the idea).

    Your background code might looks like this:

    void WorkInBackground()
    {
        var results = new List();
    
        //get results...
    
        // feed UI in packages no more than 100 items
        while (results.Count > 0)
        {
            Application.Current.MainWindow.Dispatcher.BeginInvoke(
                new Action>(FeedUI),
                DispatcherPriority.Background,
                results.GetRange(0, Math.Min(results.Count, 100)));
            results.RemoveRange(0, Math.Min(results.Count, 100));
        }
    }
    void FeedUI(List items)
    {
        // items.Count must be small enough to keep UI looks alive
        foreach (var item in items)
        {
            MyCollection.Add(item);
        }
    }
    
        

    提交回复
    热议问题