当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Method assigned to new thread not executing

问题描述:

I have a couple of DropDownLists that bind to an LDAP data source. Since they take a while to load, I want to try and mitigate the performance hit through multithreading. However, when I run the following code, the methods I've assigned to the threads do not seem to execute. There are no errors thrown at compile or run time. The DropDownLists just remain unbound. Both of the methods work fine if I do not thread them.

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();

}

网友答案:

Looks like you are trying to update UI components from the other thread. That does not work. Exception should be thrown by that component when you try to set it's properties like that, and your thread just dies.

You can do the resource-intensive computation on other thread, but then use main thread to update UI. To do that, for WPF you can use Dispatcher class, for WinForms BeginInvoke method on the control itself.

分享给朋友:
您可能感兴趣的文章:
随机阅读: