Featured post
sorting - How to create an observableCollection Sortable and multithreading -
here problem , have created sortablecollection : observablecollection , added sort method (sort colors). when sort collection principal thread , works every thing fine , works when try sort customcollection using item in collection have expetion : (the calling thread cannot access object because different thread owns it). have looked in web , found several solution , one solution
this type of solution put collection multithread insertion , removing moving operation. not custom sort. help,
wpf classes have thread affinity. means changes objects must in same thread created. difficult create user interface api thread-safe, microsoft chose keep singlethreaded , force run-time checking make sure of it.
that said, there few options have perform sort in background thread, , apply in ui thread. first option copy sortablecollection plain old list or array , perform sort in background. once background thread complete, use dispatcher execute code in ui thread. every ui element in wpf extends system.windows.threading.dispatcherobject
, extend system.windows.freezable
. dispatcherobject dispatcher execute code in ui thread.
logically, execution this:
public void backgroundsort() { list<t> items = new list<t>(this.toarray()); backgroundsortdelegate del = sort; del.begininvoke(sortcompleted, del); } private void sortcompleted(iasyncresult result) { backgroundsortdelegate del = result.asyncstate backgroundsortdelegate; list<t> items = del.endinvoke(result); this.dispatcher.invoke(()=>{this.collection = items;}); }
the short explanation of happened background worker/delegate using copy of items in list. once sort complete, calling dispatcher object , invoking action. in action assigning new sorted list our object.
the key assigning result of background work within ui thread use ui's dispatcher object. there's half dozen ways invoke background worker in c#, approach work in background thread ui thread same.
- Get link
- X
- Other Apps
Comments
Post a Comment