2013-08-22 35 views
1

我有几个绑定到LDAP数据源的DropDownLists。由于他们需要一段时间才能加载,我想尝试通过多线程来减轻性能。但是,当我运行下面的代码时,我分配给线程的方法似乎不能执行。在编译或运行时不会出现错误。 DropDownLists保持不受限制。如果我不给它们穿线,这两种方法都可以正常工作。分配给新线程的方法没有执行

if (DropDownListOwner.Items.Count == 0) 
{       
    Thread t = new Thread(BindDropDownListOwner); 
    t.Start(); 
} 

if (DropDownListAddEditRecipients.Items.Count == 0) 
{ 
    Thread t2 = new Thread(BindDropDownListAddEditRecipients); 
    t2.Start(); 
} 

// Delegate Methods 

public void BindDropDownListOwner() 
{ 
    List<KeyValuePair<string, string>> emp = EmployeeList.emplList("SAMAccountName", "DisplayName"); 
    DropDownListOwner.DataSource = emp.OrderBy(item => item.Value); 
    DropDownListOwner.DataTextField = "Value"; 
    DropDownListOwner.DataValueField = "Key"; 
    DropDownListOwner.DataBind(); 
} 

public void BindDropDownListAddEditRecipients() 
{ 
    List<KeyValuePair<string, string>> emp2 = EmployeeList.emplList("Mail", "DisplayName"); 
    DropDownListAddEditRecipients.DataSource = emp2.OrderBy(item => item.Value); 
    DropDownListAddEditRecipients.DataTextField = "Value"; 
    DropDownListAddEditRecipients.DataValueField = "Key"; 
    DropDownListAddEditRecipients.DataBind(); 
} 

回答

3

看起来像是在尝试从其他线程更新UI组件。这是行不通的。 当您尝试设置它的属性时,该组件会引发异常,并且线程刚刚死亡。

您可以在其他线程上执行资源密集型计算,然后使用主线程来更新UI。为此,对于WPF,您可以使用Dispatcher类,用于控件本身的WinForms BeginInvoke方法。

+0

尝试使用单独的线程更新UI组件确实是个问题。虽然我得到它的工作,但我没有注意到任何性能改进。看起来,在等待DOM构建两个每个具有一千个元素的html选择时发生缓慢。 –