最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

加载 ObservableCollection<string>;有任务

网站源码admin14浏览0评论
本文介绍了加载 ObservableCollection<string>;有任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在尝试加载我们活动目录中的所有用户并将它们显示在列表框中.但是,如果我像往常一样这样做,我会长时间冻结 UI 线程.那么无论如何我可以使用一个任务在后台线程上填充这个集合,同时在我插入新名称时仍然让列表框更新?

I am trying to load all the users in our active directory and display them in a ListBox. However if I do this like normal I freeze the UI thread for a long time. So is there anyway I can use a task to fill this collection up on a background thread while still getting the listbox to update as I insert new names?

推荐答案

由于你不能在一个单独的线程(或任务,什么的)中加载所有数据然后填充 ObservableCollection,你可以将当前的 Dispatcher 传递给操作和使用其 InvokeAsync 方法将元素一一添加到 UI 线程中的 Observable 集合中.像这样:

As you cannot load all the data in a separate thread (or task, whatever) and then fill the ObservableCollection, you can pass the current Dispatcher to the operation and use its InvokeAsync method to add the elements one by one to the Observable collection in the UI thread. Something like this:

public void FetchAndLoad()
    {
        // Called from the UI, run in the ThreadPool
        Task.Factory.StartNew( () =>
        this.FetchAsync(e => this.Dispatcher.InvokeAsync(
            () => this.observableCollection.Add(e)
            )
        ));
    }

    public void Fetch(Action<string> addDelegate)
    {
                    // Dummy operation
        var list = new List<string>("Element1", "Element2");

        foreach (var item in list)
            addDelegate(item);
    }

不过,我会分批进行,具体取决于元素的数量.

I would do that in batches, though, depending on the number of elements.

这篇关于加载 ObservableCollection<string>;有任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

发布评论

评论列表(0)

  1. 暂无评论