当ObservableCollection列表被UI线程占用时,如果在异步线程中调用ObservableCollection,会弹出以下异常:
private void Button1_OnClick(object sender, RoutedEventArgs e) { var viewModel = this.DataContext as ViewModel; Task.Run(() => { Application.Current.Dispatcher.Invoke(() => { //此段不会报错 viewModel.ItemsSource.Add("test"); }); }); }
可解决;本人再做串口通信时在收消息的时候遇到该问题,琢磨出这种方案,欢迎指正!