带有Join()的WPF线程阻止UI线程

时间:2014-01-14 17:00:24

标签: wpf multithreading listbox thread-safety

我的主要课程:

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.
}

我知道thread.Join()导致阻塞我的UI线程。

我该如何预防?

我可以使用BackgroundWorker执行此操作,但我想知道如何继续使用Thread。

PLUS)

在线程部分,我可以像这样分开任务:

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

1 个答案:

答案 0 :(得分:3)

让你的线程回调到UI来设置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();
}

如果可能,请在C#5中使用异步 - 这样会更清晰:

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