Monday, January 18, 2010

DispatcherPriority

I had a very tough problem today. The following code did not work correctly:

var books = _bookRepository.All;
 
Dispatcher.Invoke(
    new ThreadStart(delegate
                        {
                            foreach (Book book in books)
                            {
                                CatalogItems.Add(new BookViewModel(book));
                            }
 
                            OnLoaded(this, EventArgs.Empty);
                            OnPropertyChanged("CatalogItems");
                        }),
    DispatcherPriority.ApplicationIdle);

When I run the code above the first time, the debugger didn’t even break into the dispatched code. The subsequent calls were fine.

Finally I realized that DispatcherPriority.ApplicationIdle should be changed to DispatcherPriority.Normal – and everything was fine. Don’t forget to check the DispatcherPriority value of the dispatcher! It’s hard to debug and hard to recognize.

These are the possible dispatcher priority levels:

Priority

Description

Inactive

Work items are queued but not processed.

SystemIdle

Work items are only dispatched to the UI thread when the system is idle. This is the lowest priority of items that are actually processed.

ApplicationIdle

Work items are only dispatched to the UI thread when the application itself is idle.

ContextIdle

Work items are only dispatched to the UI thread after higher-priority work items are processed.

Background

Work items are dispatched after all layout, rendering, and input items are processed.

Input

Work items are dispatched to the UI thread at the same priority as user input.

Loaded

Work items are dispatched to the UI thread after all layout and rendering are complete.

Render

Work items are dispatched to the UI thread at the same priority as the rendering engine.

DataBind

Work items are dispatched to the UI thread at the same priority as data binding.

Normal

Work items are dispatched to the UI thread with normal priority. This is the priority at which most application work items should be dispatched.

Send

Work items are dispatched to the UI thread with the highest priority.

 

Link: Build More Responsive Apps With The Dispatcher (MSDN)