c# – 从另一个线程更新ObservableCollection

前端之家收集整理的这篇文章主要介绍了c# – 从另一个线程更新ObservableCollection前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我一直在尝试处理Rx库并使用MVVM在 WPF中进行处理.我将我的应用程序分解为诸如存储库和viewmodel之类的组件.我的存储库能够一个接一个地提供学生集合,但是当我尝试添加到View绑定的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; }
}

猜你在找的C#相关文章