在另一个线程上使用IEnumrable填充ListBox(winforms)
我想知道填充WinForm的ListBox控件的最佳方法是什么,根据无线电btn填充?
我看到一些建议使用foreach循环遍历列表中的每个对象,并将它们添加到listBox.items.Add(),但这似乎是一个非常糟糕的主意,因为来自rabio btn 1的列表返回一个包含10.000条记录的列表(需要一段时间才能循环播放,并且在循环时会冻结UI,糟糕的坏主意)。
有没有更好的方法来做到这一点,也许在一个单独的任务停止UI冻结?
private void PopulateListBox() { foreach (var item in Controller.ReturnBigResultSet()) this.Invoke((MethodInvoker)(() => listBox1.Items.Add(item))); }
更新:使用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()); 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毫秒)。
您可能希望放入另一个线程的部分是加载数据而不是向ListBox
添加数据。
要向ListBox
添加项目,只需使用AddRange
:
this.listBox1.AddRange(array);
这相当于使用下面的代码。 首先调用ListBox
BeginUpdate
方法,然后使用循环将项Add
到Items
集合,最后调用EndUpdate
:
this.listBox1.BeginUpdate(); foreach (var item in array) { this.listBox1.Items.Add(item); } this.listBox1.EndUpdate();
看一下AddRange
方法的源代码 。