正在从另一个线程更新ObservableCollection

本文关键字:更新 ObservableCollection 线程 另一个 | 更新日期: 2023-09-27 18:25:08

我一直在尝试处理Rx库,并用MVVM在WPF中解决它。我将应用程序分解为存储库和ViewModel等组件。我的存储库能够一个接一个地提供学生集合,但当我试图将其添加到绑定到View的ObservableCollection中时,它引发了线程错误。我会在上面放一些指针,让它为我工作。

正在从另一个线程更新ObservableCollection

您需要使用正确设置同步上下文

ObserveOn(SynchronizationContext.Current)

查看此博客文章

http://10rem.net/blog/2011/02/17/asynchronous-web-and-network-calls-on-the-client-in-wpf-and-silverlight-and-net-in-general

例如。

这里有一个对我有用的例子:

<Page.Resources>
    <ViewModel:ReactiveListViewModel x:Key="model"/>
</Page.Resources>
<Grid DataContext="{StaticResource model}">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <Button Content="Start" Command="{Binding StartCommand}"/>
    <ListBox ItemsSource="{Binding Items}" Grid.Row="1"/>
</Grid>
public class ReactiveListViewModel : ViewModelBase
{
    public ReactiveListViewModel()
    {
        Items = new ObservableCollection<long>();
        StartCommand = new RelayCommand(Start);
    }
    public ICommand StartCommand { get; private set; }
    private void Start()
    {
        var observable = Observable.Interval(TimeSpan.FromSeconds(1));
        //Exception: This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread.
        //observable.Subscribe(num => Items.Add(num));
        // Works fine
        observable.ObserveOn(SynchronizationContext.Current).Subscribe(num => Items.Add(num));
        // Works fine
        //observable.ObserveOnDispatcher().Subscribe(num => Items.Add(num));
    }
    public ObservableCollection<long> Items { get; private set; }
}

您的代码是否在后台线程上运行?由于它会影响UI,绑定到View的ObservableCollection只能在UI/Dispatcher线程上更新。

有关类似问题,请参阅WPF ObservableCollection线程安全。

对UI的任何更改都应由Dispatcher线程完成。如果您让另一个线程不断更改视图模型,那么一个好的做法是强制属性设置器使用调度器线程。在这种情况下,您要确保不会更改另一个线程上的UI元素。

尝试:

public string Property 
{ 
   set 
    { 
      Dispatcher.BeginInvoke(()=> _property = value ) ; 
      OnPropertyChanged("Property");  
    } 
   get 
    { 
      return _property; 
    }
}