#ObservableCollection
private ObservableCollection<string> items = new ObservableCollection<string>();
private void UpdateCollectionFromBackgroundThread(string newItem)
{
// 检查当前是否在UI线程
if (Application.Current.Dispatcher.CheckAccess())
{
// 如果已经在UI线程,直接添加
items.Add(newItem);
}
else
{
// 如果不在UI线程,使用Dispatcher Invoke或BeginInvoke委托回UI线程
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
// 在UI线程中执行集合的更新操作
items.Add(newItem);
}));
}
}
// 如果需要排序或过滤等操作,确保也在UI线程执行
}
// 假设你有一个按钮点击事件或类似的操作来触发后台更新
private void Button_Click(object sender, RoutedEventArgs e)
{
Task.Run(() => UpdateCollectionFromBackgroundThread("New Item from Background Thread"));
}