C# 方法分配给未执行的新线程

C# 方法分配给未执行的新线程,c#,multithreading,C#,Multithreading,我有几个DropDownLists绑定到LDAP数据源。因为加载它们需要一段时间,所以我想尝试通过多线程减轻性能的影响。但是,当我运行下面的代码时,我分配给线程的方法似乎不会执行。编译或运行时没有抛出错误。DropDownList只是保持未绑定状态。如果我不使用线程,这两种方法都可以很好地工作 if (DropDownListOwner.Items.Count == 0) { Thread t = new Thread(BindDropDo

我有几个DropDownLists绑定到LDAP数据源。因为加载它们需要一段时间,所以我想尝试通过多线程减轻性能的影响。但是,当我运行下面的代码时,我分配给线程的方法似乎不会执行。编译或运行时没有抛出错误。DropDownList只是保持未绑定状态。如果我不使用线程,这两种方法都可以很好地工作

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();
}
if(DropDownListOwner.Items.Count==0)
{                        
螺纹t=新螺纹(BindDropDownstowner);
t、 Start();
}
if(dropDownlowstatedEditRecipients.Items.Count==0)
{
线程t2=新线程(BindDropDownstaddEditRecipients);
t2.Start();
}
//委托方法
公共无效BindDropDownlowsTowner()
{
List emp=EmployeeList.emplList(“SAMAccountName”、“DisplayName”);
DropDownListOwner.DataSource=emp.OrderBy(item=>item.Value);
DropDownListOwner.DataTextField=“Value”;
DropDownListOwner.DataValueField=“Key”;
DropDownListOwner.DataBind();
}
public void bindDropDownloadStatedEditRecipients()
{
List emp2=EmployeeList.employList(“邮件”、“显示名称”);
DropDownListAddEditRecipients.DataSource=emp2.OrderBy(item=>item.Value);
DropDownlowstatedEditRecipients.DataTextField=“Value”;
dropDownlowstatededitRecipients.DataValueField=“Key”;
DropDownListAddEditRecipients.DataBind();
}

看起来您正试图从另一个线程更新UI组件。这是行不通的。 当您试图这样设置组件的属性时,该组件应该抛出异常,而您的线程就死了


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

尝试使用单独的线程更新UI组件确实是个问题。但在我让它工作之后,我没有注意到任何性能改进。在等待DOM生成两个html选择时,似乎出现了速度缓慢的情况,每个html选择都有超过1000个元素。