WPF Thread with Join() blocks UI thread

My main class:

List<string> myList;
...
private void Button_Click(object sender, RoutedEventArgs e)
{
    Thread thread = new Thread(() =>
    {
        myList = myClass.getListData(); // This takes for awhile.
    });
    thread.start();
    thread.join(); // So I want my program to wait the thread is done here.

    listBox1.ItemsSource = myList; // Then, update the listbox.
}

I know thread.Join() causes blocking my UI thread.

How do I prevent?

I could do this with BackgroundWorker, but I want to know how keep using Thread.

PLUS)

In threading part, I can separate task like this:

Thread thread = new Thread(() => {
    myClass.doSomething(); // Adding data into a list in the other class.
    myList = myClass.getList(); // Get the list from the other class.
});
Jon Skeet
people
quotationmark

Make your thread call back to the UI to set the ItemsSource:

private void Button_Click(object sender, RoutedEventArgs e)
{
    Thread thread = new Thread(() =>
    {
        myList = myClass.getListData();
        Action uiAction = () => listBox1.ItemsSource = myList;
        Dispatcher.Invoke(uiAction); // Execute on the UI thread
    });
    thread.Start();
}

If possible, use asynchrony in C# 5 though - that would be much cleaner:

private async void Button_Click(object sender, RoutedEventArgs e)
{
    myList = await myClass.GetListDataAsync();
    listBox1.ItemsSource = myList;
}

people

See more on this question at Stackoverflow