在另一个线程上使用IEnumrable填充ListBox(winforms) [英] Populate ListBox with a IEnumrable on another thread (winforms)
问题描述
我想知道哪种方法是填充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遍历列表的每个对象,然后将它们添加()到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).
有没有更好的方法可以做到这一点,也许在单独的Task中可以阻止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
.
To add items to ListBox
it's enough to use AddRange
:
this.listBox1.AddRange(array);
这等同于使用下面的代码.首先调用 Add
项目添加到Items
集合,最后调用
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();
Take a look at source code of AddRange
method.
这篇关于在另一个线程上使用IEnumrable填充ListBox(winforms)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!