使用BindingSource很慢?
我有一个 C# Windows 窗体项目,其中的窗体包含 2 个列表框和一个按钮。 在 FormLoad 上,左侧列表框填充了一个列表(约 1800 个项目),其中包含有关证券的信息(ID 和名称),当用户单击该按钮时,所有证券都会从左侧列表框移动到右侧。
当我不使用 BindingSources 时,即我直接使用 ListBoxes 的 Items 属性,移动过程需要几秒钟:
private void button1_Click(object sender, EventArgs e)
{
while (listBox1.Items.Count > 0)
{
Security s = listBox1.Items[0] as Security;
listBox1.Items.Remove(s);
listBox2.Items.Add(s);
}
}
但是,当我使用 BindingSources 时,需要几分钟:
listBox1.DataSource = bindingSource1;
listBox2.DataSource = bindingSource2;
...
private void MainForm_Load(object sender, EventArgs e)
{
ICollection<Security> securities = GetSecurities();
bindingSource1.DataSouce = securities;
}
private void button1_Click(object sender, EventArgs e)
{
while (bindingSource1.Count > 0)
{
bindingSource1.Remove(s);
bindingSource2.Add(s);
}
}
BindingSource-way 的原因是什么需要这么长时间? 有什么办法可以让它更快吗?
I have a C# Windows Forms project with a Form containing 2 ListBoxes and a button.
On FormLoad the left ListBox is filled with a list (about 1800 items) containing information about Securities (ID and Name) and when the user clicks on the button all the securities are moved from the left listbox to the right.
When I'm not using BindingSources, i.e. I'm directly using the Items property of the ListBoxes the moving process takes a few seconds:
private void button1_Click(object sender, EventArgs e)
{
while (listBox1.Items.Count > 0)
{
Security s = listBox1.Items[0] as Security;
listBox1.Items.Remove(s);
listBox2.Items.Add(s);
}
}
But, when I'm using BindingSources it takes several minutes:
listBox1.DataSource = bindingSource1;
listBox2.DataSource = bindingSource2;
...
private void MainForm_Load(object sender, EventArgs e)
{
ICollection<Security> securities = GetSecurities();
bindingSource1.DataSouce = securities;
}
private void button1_Click(object sender, EventArgs e)
{
while (bindingSource1.Count > 0)
{
bindingSource1.Remove(s);
bindingSource2.Add(s);
}
}
What's the reason for the BindingSource-way to take so much longer?
Is there any way to make it faster?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该在在对 BindingSource 进行大量更改之前先更改 BindingSource,然后在完成后重置。然后您可以使用 ResetBindings 刷新绑定的控件。
您还应该使用 BeginUpdate/EndUpdate 包装列表框项目上的大量操作,以避免重绘。这可能是造成经济放缓的主要原因。
You should unset the RaiseListChangedEvents property on the BindingSource before you do a big set of changes on the BindingSource and reset if after you're done. Then you can use ResetBindings to refresh the bound controls.
You should also wrap large sets of operations on listbox items with a BeginUpdate/EndUpdate to avoid redrawing. This is likely what's causing the most of the slowdown.
试试这个
try this
好的,解决了。
我必须操作底层集合,然后在最后重置绑定。现在它几乎立即移动:)
Ok, solved it.
I have to manipulate the underlying collection and then reset bindings at the end. Now it's almost instantly moving :)