Marcus Santodonato
Marcus Santodonato

Reputation: 136

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

Upvotes: 1

Views: 100

Answers (1)

alex
alex

Reputation: 12654

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.

Upvotes: 3

Related Questions