Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>WPF classes have thread affinity. What this means is that all changes to those objects must be in the same thread where they were created. It truly is difficult to create a user interface API that is thread-safe, so Microsoft chose to keep it singlethreaded and force run-time checking to make sure of it.</p> <p>That said, there are a few options you have to perform your sort in a background thread, and then apply it in the UI thread. The first option is to copy your SortableCollection into a plain old List or Array and perform the sort in the background. Once the background thread is complete, you use a Dispatcher to execute code in the UI thread. Every UI element in WPF extends <code>System.Windows.Threading.DispatcherObject</code> and most extend <code>System.Windows.Freezable</code>. The DispatcherObject is where you get the Dispatcher to execute code in the UI thread.</p> <p>Logically, the execution would be something like this:</p> <pre><code>public void BackgroundSort() { List&lt;T&gt; items = new List&lt;T&gt;(this.ToArray()); BackgroundSortDelegate del = Sort; del.BeginInvoke(SortCompleted, del); } private void SortCompleted(IAsyncResult result) { BackgroundSortDelegate del = result.AsyncState as BackgroundSortDelegate; List&lt;T&gt; items = del.EndInvoke(result); this.Dispatcher.Invoke(()=&gt;{this.Collection = items;}); } </code></pre> <p>The short explanation of what happened is that the background worker/delegate is using a copy of the items in this list. Once the sort is complete, we are calling the Dispatcher object and invoking an action. In that action we are assigning the new sorted list back to our object.</p> <p>The key to assigning the result of any background work within the UI thread is to use the UI's Dispatcher object. There's actually probably a half dozen ways to invoke a background worker in C#, but the approach to get your work in a background thread into the UI thread is the same.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload