views:

49

answers:

1

Hi,

Platform: WPF, .NET 4.0, C# 4.0

Problem: In the Mainwindow.xaml i have a ListBox bound to a Customer collection which is currently an ObservableCollection< Customer >.

ObservableCollection<Customer> c = new ObservableCollection<Customer>();

This collection can be updated via multiple sources, like FileSystem, WebService etc.

To allow parallel loading of Customers I have created a helper class

public class CustomerManager(ref ObsevableCollection<Customer> cust)

that internally spawns a new Task (from Parallel extensions library) for each customer Source and adds a new Customer instance to the customer collection object (passed by ref to its ctor).

The problem is that ObservableCollection< T> (or any collection for that matter) cannot be used from calls other than the UI thread and an exception is encountered:

"NotSupportedException – This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread."

I tried using the

System.Collections.Concurrent.ConcurrentBag<Customer>

collection but it doesnot implement INotifyCollectionChanged interface. Hence my WPF UI won't get updated automatically.

So, is there a collection class that implements both property/collection change notifications and also allows calls from other non-UI threads?

By my initial bing/googling, there is none provided out of the box.

Edit: I created my own collection that inherits from ConcurrentBag< Customer > and also implements the INotifyCollectionChanged interface. But to my surprise even after invoking it in separate tasks, the WPF UI hangs until the task is completed. Aren't the tasks supposed to be executed in parallel and not block the UI thread?

Thanks for any suggestions, in advance.

A: 

You may try the implementation in this blog post.

Darin Dimitrov
Thanks. Looks good. Trying it out!
Vaibhav
Hi Darin, I used the collection class as mentioned in the blog post. As mentioned in my question, i was able to merge both Concurrent and Notification changes by creating my own collection class inheriting and implement the required class/interfaces, but the UI is getting blocked. The primary reason of using the Tasks was to have UI responsiveness.That isn't working still! Thanks a lot for your suggestion.
Vaibhav