Example of Calling Dispatcher Directly from non-UI code in .NET WPF

.NET’s Threading module isn’t the best, it has the look of a model that was designed by the type of software people who like to keep practical multi-threading a good long arm’s length away. It’s workable but sometimes it requires that you jump through hoops to do simple everyday things with threads – like updating a UI element from a non UI thread etc. You may see errors akin to the following:

“Must create DependencySource on same Thread as the DependencyObject.”

“This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread.”

To get around this all a .NET developer needs to do is to remember a few ritualistic looking invocations to appease the .NET small gods – but of course I can never remember the details so am recording one such here:

To dispatch to the UI from a non-UI thread and non-UI code, use something like the following:

using System.Windows;
Application.Current.Dispatcher.Invoke(new Action (() => Thumbnails.Add(thumbnail)));
1 reply

Comments are closed.