mrbradleyt
mrbradleyt

Reputation: 2364

What is the use of a Dispatcher Object in WPF?

What is the use of a Dispatcher Object in WPF?

Upvotes: 23

Views: 24103

Answers (3)

arik
arik

Reputation: 367

Almost every WPF element has thread affinity. This means that access to such an element should be made only from the thread that created the element. In order to do so, every element that requires thread affinity is derived, eventually, from DispatcherObject class. This class provides a property named Dispatcher that returns the Dispatcher object associated with the WPF element.

The Dispatcher class is used to perform work on its attached thread. It has a queue of work items and it is in charge of executing the work items on the dispatcher thread.

You can find on the following link some more details on the subject: https://www.codeproject.com/Articles/101423/WPF-Inside-Out-Dispatcher

Upvotes: 28

user3856437
user3856437

Reputation: 2377

In my experience we use Prism Event Aggregator. When the event happens it calls the Dispatcher.Invoke() to update the UI. This is because only the Dispatcher can update the objects in your UI from a non-UI thread.

public PaginatedObservableCollection<OrderItems> Orders { get; } = new PaginatedObservableCollection<OrderItems>(20);

_eventAggregator.GetEvent<OrderEvent>().Subscribe(orders =>
{
      MainDispatcher.Invoke(() => AddOrders(orders));
});

private void AddOrders(List<OrderItems> orders)
{
     foreach (OrderItems item in orders)
     Orders.Add(item);
}

Upvotes: 0

GEOCHET
GEOCHET

Reputation: 21323

A dispatcher is often used to invoke calls on another thread. An example would be if you have a background thread working, and you need to update the UI thread, you would need a dispatcher to do it.

Upvotes: 16

Related Questions