InvalidOperationException - Cannot use a DependencyObject that Belongs to a Different Thread than its Parent Freezable
Environment
Product Version | 2021.2.511 |
Product | Telerik UI for WPF |
Description
An "InvalidOperationException: Cannot use a DependencyObject that belongs to a different thread than its parent Freezable." is thrown if you try to access a Brush or other Freezable from a different thread.
Solution
Any public static members of the Freezable type are thread safe. Any instance members, however, are not guaranteed to be thread safe.
When the IsFrozen property is false, a Freezable object can be accessed only from the thread on which it was created. Attempting to access it from another thread throws an InvalidOperationException. The Invoke and BeginInvoke methods provide support for marshalling to the correct thread.
When their IsFrozen property is true, Freezable objects are free-threaded. For more information, see Freezable Objects Overview.
Thus, to overcome this exception, you need to freeze the Freezable object before using it:
Example 1: Freeze the Freezable object
var brush = (Brush)new BrushConverter().ConvertFrom("#4CAF50");
if (brush.CanFreeze)
{
brush.Freeze();
}