[英]Adding Items to ListView too slow in C#
我想将项目添加到listview控件。 这是一些代码:
this.lView.ListViewItemSorter = null;
ListViewItem[] lvitems = new ListViewItem[ListMyObjects.Count];
int index = 0;
foreach (MyObject object in ListMyObjects)
{
ListViewItem item = new ListViewItem();
item.Text = object.Name;
lvitems[index++] = item;
}
this.lView.BeginUpdate();
this.lView.Items.AddRange(lvitems); // Slow in here with debugger
this.lView.EndUpdate();
我只添加了大约1000个项目,但是速度非常慢。 完成大约需要15秒。 为什么有人知道原因? 预先感谢。
编辑 :
我以前自定义过listview。
public partial class MyListView: ListView
{
public MyListView()
{
InitializeComponent();
this.View = View.Details;
this.FullRowSelect = true;
this.DoubleBuffered = true;
}
private bool mCreating;
private bool mReadOnly;
protected override void OnHandleCreated(EventArgs e)
{
mCreating = true;
base.OnHandleCreated(e);
mCreating = false;
}
public bool ReadOnly
{
get { return mReadOnly; }
set { mReadOnly = value; }
}
protected override void OnItemCheck(ItemCheckEventArgs e)
{
if (!mCreating && mReadOnly) e.NewValue = e.CurrentValue;
base.OnItemCheck(e);
}
}
我这样做是因为我不想在使用多个线程时挂起。 我不知道这对它有什么影响?
您可以通过启用虚拟模式来使其更快。
但是,这将需要一些工作。
添加多个项目的首选方法是使用AddRange()方法 。 但是,如果必须一一添加项,则可以在循环中使用BeginUpdate()和EndUpdate()方法。 以下是来自MSDN的
将多个项目添加到ListView的首选方法是使用ListView.ListViewItemCollection的AddRange方法(通过ListView的Items属性访问)。 这使您可以通过一次操作将一系列项目添加到列表中。 但是,如果要使用ListView.ListViewItemCollection类的Add方法一次添加一项,则可以使用BeginUpdate方法来防止控件在每次添加项目时重新绘制ListView。
应用程序学可以提供更具体系结构的解决方案,但是如果您的域对象很大,则可能会导致瓶颈(阅读注释,听起来好像它们在减慢它的速度)。 在到达表示层之前,您可以将它们展平为一些(非常简单的)域传输对象(DTO):实际上只是一堆吸气剂。
像AutoMapper这样的工具可能会带走很多驴子的工作
这样,您的域对象就位于业务逻辑域(它们所属的域)中,而表示层则只是从DTO获取需要的数据。
很抱歉非基于代码的建议:)祝您好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.