I know that it's not allowed to create WPF UI elements such as a SolidColorBrush in a non-ui-thread.
I did it by accident and instead of WPF telling me that this is not allowed, I got a ArgumentOutOfRangeException in MultipleCopiesCollection.get_item():
System.Windows.Controls.MultipleCopiesCollection.get_Item(Int32 index) System.Windows.Data.ListCollectionView.InternalItemAt(Int32 index) System.Windows.Data.ListCollectionView.GetItemAt(Int32 index) System.Windows.Controls.ItemCollection.GetItemAt(Int32 index) System.Windows.Controls.DataGridCellsPanel.VirtualizeChildren(List1 blockList, IItemContainerGenerator generator)
System.Windows.Controls.DataGridCellsPanel.GenerateAndMeasureChildrenForRealizedColumns(Size constraint)
System.Windows.Controls.DataGridCellsPanel.MeasureOverride(Size constraint)
System.Windows.FrameworkElement.MeasureCore(Size availableSize)
System.Windows.UIElement.Measure(Size availableSize)
MS.Internal.Helper.MeasureElementWithSingleChild(UIElement element, Size constraint)
System.Windows.Controls.ItemsPresenter.MeasureOverride(Size constraint)
System.Windows.FrameworkElement.MeasureCore(Size availableSize)
[... a lot more FrameworkElement / Measure call stack]
I'm using the SolidColorBrush in a Style Setter of a DataGridCell in a DataGrid.
I expect WPF to tell me that I can't create the SolidColorBrush in the Non-UI-Thread. Does anyone know why there is no proper exception for my error?
PS: It happened to me because some UI actions in Outlook / VSTO AddIns seem to be called from the outlook message loop and lead to the fact that SynchronizationContext.Current is null. In this case code after an await statement might run in a non-ui-thread.
Found out that between the thousands of exceptions one Exception was
Error: Must create DependencySource on same Thread as the DependencyObject even by using Dispatcher.
So I just had to look at the right exception...
It is a misconception that creating a
SolidColorBrush(or any otherFreezable) in a thread other than the UI thread is "not allowed".It is allowed, you just have to make sure to call
Freeze()before you use the object in the UI thread.From the documentation: