在另一个线程(winforms)上使用 IEnumrable 填充 ListBox [英] Populate ListBox with a IEnumrable on another thread (winforms)

查看:19
本文介绍了在另一个线程(winforms)上使用 IEnumrable 填充 ListBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道填充 WinForm 的 ListBox 控件的最佳方法是什么,根据无线电 btn 填充?

I'm wondering what would be the best way to populate a ListBox control of a WinForm, populated depending on a radio btn?

我已经看到一些建议使用 foreach 循环遍历列表中的每个对象,并将它们 Add() 到 listBox.items.Add(),但这似乎是一个非常糟糕的主意,因为列表来自rabio btn 1 返回一个包含 10.000 条记录的列表(循环需要一些时间,并且 UI 在循环时冻结,这是个坏主意).

I have seen some suggestions to use a foreach to loop over each object of my list, and Add() them to the listBox.items.Add(), but this seems to be a really bad idea, since the list from rabio btn 1 returns a list with 10.000 records (takes quiet some time to loop over, and the UI freeze while looping, bad bad idea).

有没有更好的方法来做到这一点,也许在一个单独的任务中停止 UI 冻结??

Is there any better way to do this, and maybe in a seperated Task to stop UI freeze??

private void PopulateListBox()
{
    foreach (var item in Controller.ReturnBigResultSet())
            this.Invoke((MethodInvoker)(() => listBox1.Items.Add(item)));
}

更新:使用 AddRange 的代码块:

UPDATE: Code block using AddRange:

var watch = new Stopwatch();
watch.Start();
var list = Controller.GetAllEntries().ToArray();
Debug.WriteLine("List returned in {0}s with a size of {1}", watch.Elapsed.TotalSeconds, list.Count<Lejlighed>());
watch.Restart();
listBox1.Items.AddRange(list);
watch.Stop();
Debug.WriteLine("Added {0} items in {1}s", listBox1.Items.Count, watch.Elapsed.TotalSeconds);

输出是:

List returned in 3.8596527s with a size of 19022
Added 19022 items in 1.9223412s

推荐答案

您不需要从另一个线程中填充 ListBox.如果您使用正确的方法来填充它,填充 10000 个项目需要很短的时间(对我来说 200-300 毫秒).

You don't need to populate the ListBox from in another thread. If you use a correct way to populate it, populating 10000 items takes a short time (for me 200-300 ms).

您可能想要放入另一个线程的部分是加载数据而不是将数据添加到 ListBox.

The part that you may want to put in another thread is loading data not adding data to ListBox.

要向 ListBox 添加项目,使用 AddRange:

To add items to ListBox it's enough to use AddRange:

this.listBox1.AddRange(array);

相当于使用下面的代码.首先调用 ListBox 的 >BeginUpdate 方法,然后使用循环将 Add 项添加到 Items 集合中,最后调用 EndUpdate:

Which is equivalent to using below code. First call BeginUpdate method of ListBox and then use a loop to Add items to Items collection and at last call EndUpdate:

this.listBox1.BeginUpdate();
foreach (var item in array)
{
    this.listBox1.Items.Add(item);
}
this.listBox1.EndUpdate();

看看 来源AddRange 方法的代码.

Take a look at source code of AddRange method.

这篇关于在另一个线程(winforms)上使用 IEnumrable 填充 ListBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆