开发者

Delete ObservableCollection Items From Different Thread Mystery

I am using an ObservableCollection implementation that allows creating/updating/deleti开发者_如何学JAVAng collection items from a different thread than the UI thread. Everything works fine except than when im updating the collection from the UI, i cant delete its items anymore from the different thread.

The ObservableCollectionEx implementation is taken from : http://geekswithblogs.net/NewThingsILearned/archive/2008/01/16/have-worker-thread-update-observablecollection-that-is-bound-to-a.aspx

Please Help! Thanks

EDIT :

Ok. To clear things up : I'm implementing an ObservableCollection with a context sync. It means that when i add/delete/update an item on the collection, i correspondingly do the same on the ObjectContext. When i checked my exception, i saw that it is raised when invoking the ObjectContext.DeleteObject() method, after the item was updated from the UI thread. So it basically got nothing to do with the ObservableCollection but with the ObjectContext itself. The exception though is identical to the exception i first got when trying to delete item on the collection from another thread (the excecption is : "This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread."

The Plot Thickens....

Many Thanks...


Are you sure that problem is in that?

Next code works fine:

        private readonly ObservableCollectionEx<int> collection = new ObservableCollectionEx<int>();

        public MainWindow()
        {
            InitializeComponent();

            this.collection.Add(30);
            this.collection.Add(50);
            this.collection.Add(70);

            new Thread(() =>
            {
                this.collection.Add(100);
            }).Start();

            new Thread(() =>
            {
                this.collection.Add(110);
                this.collection.Add(120);
            }).Start();

// Update and delete in UI thread
            this.collection.Remove(30);
            this.collection[0] = 1130;

            new Thread(() =>
            {
// Delete in worker thread after modification in UI thread
                this.collection.Remove(1130);
            }).Start();
        }

Could you provide some code where error occured? Besides, it's unclear what exactly goes wrong? Have you got any exception or deleting in worker thread hasn't changed collection or it has changed collection incorrectly or your code has even hanged up?


The solution to the above is to perform the delete object on the context within a Dispatcher.Invoke :

Dispatcher.Invoke(new Action(() =>
        { 
             context.DeleteObject(obj);
        }));

It is better described in the following link : http://social.msdn.microsoft.com/Forums/en/wpf/thread/793ebe28-2bba-4324-ba70-7a561a695b2e

Thanks

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜