我的主要课程:
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.
});
答案 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;
}