2012-02-20 170 views
5

更新一個ObservableCollection我一直在試圖獲得的Rx庫手柄和與MVVM工作它在WPF。我將我的應用程序分解爲諸如存儲庫和ViewModel之類的組件。我的存儲庫能夠一個一個地提供學生集合,但是當我嘗試添加到視圖綁定的ObservableCollection中時,它會引發線程錯誤。我想了解一些指針以便爲我工作。從另一個線程

+0

可能重複(http://stackoverflow.com/questions/2104614/updating-an-observablecollection-in-a-separate-thread ) – 2012-02-20 17:32:59

+0

嘗試下面的鏈接,它提供了一個線程安全的解決方案,可以從任何線程運行,並且可以通過多個UI線程綁定到:http://www.codeproject.com/Articles/64936/Multithreaded-ObservableImmutableCollection – Anthony 2014-04-15 19:22:06

回答

8

您需要設置同步環境中使用

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; } 
} 
+0

此方法工作if代碼位於Xamls代碼後面,但我需要ViewModel來添加一個實體。我的源代碼是從ViewModel調用的異步服務。當時SynchronitaionContext.Current在ViewModel – 2012-02-21 08:47:55

+0

中沒有任何值,我添加了一個適用於我的示例。請注意,我已經通過NuGet添加了Rx-Main和Rx-WPF。 – Phil 2012-02-21 08:48:58

+0

我的代碼或多或少是相同的,但我的集合獲取和分配發生在構造函數中。此外,我正在使用Unity來解決課程。我已經在這裏添加了一個詳細的代碼http://stackoverflow.com/questions/9377290/synchronizationcontext-current-is-null-on-resolving-with-unity-in-wpf – 2012-02-21 12:05:09

1

是運行在後臺線程的代碼?因爲它會影響UI,所以只能在UI/Dispatcher線程上更新View綁定的ObservableCollection。

WPF ObservableCollection Thread Safety了類似的問題。

1

到用戶界面的任何變化都必須經Dispatcher線程來完成。如果您有anthoer線程不斷更改視圖模型,最好的做法是強制屬性設置器使用調度程序線程。在這種情況下,你要確保你不會改變另一個線程上的UI元素。

嘗試:[在一個單獨的線程更新一個ObservableCollection]的

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