#175 – Freeze Graphical Objects That You Don’t Intend to Modify

For performance purposes, it’s best to freeze graphical objects (e.g. brushes) if you don’t intend to modify them.  You must also freeze an object if you intend to reference it from a thread other than the thread that created it.

You can freeze an object in code, using the Freeze method.

            // SolidColorBrush, created in XAML, not frozen
            bool frozen = tealBrush.IsFrozen;    // frozen = false

            if (tealBrush.CanFreeze)

            frozen = tealBrush.IsFrozen;         // frozen = true

You can also freeze an object in XAML, when it is declared, with the addition of an XML namespace.

<Window x:Class="WpfApplication4.MainWindow"
        Title="MainWindow" Height="350" Width="525" >
        <SolidColorBrush x:Key="tealBrush" Color="Teal" po:Freeze="True"/>

#173 – You Can Put Freezable Objects Into a Read-Only State

The idea of an object deriving from Freezable is that it normally is in a read/write state, but can be explicitly put into a read-only state using the Freeze method.  A frozen object can be used more efficiently in WPF because it doesn’t need to notify consumers of the object that its value has changed.

Graphical objects in WPF like brushes and 3D geometries derive from Freezable.  Initially unfrozen, a change to one of these objects results in consumers of the objects being notified of the change.

If you have an object deriving from Freezable that you don’t plan to change, you can make the object read-only using the Freeze method.

            // Freeze this object, making it read-only (since we don't plan on changing it)
            if (theBrush.CanFreeze)

After freezing the object, if you try modifying it, you’ll get an InvalidOperationException.  But WPF will be more efficient in its use of the object.