Monday, March 7, 2011

Predefined Brushes Are Already Frozen

The SolidColorBrush objects returned from the Brushes class are in a frozen state, which means they can no longer be altered. freezing is implemented in the Freezable class, from which Brush inherits. If the CanFreeze property of a Freezable object is true, it's possible to call the Freeze method to render the object frozen and unchangeable. The IsFrozen property indicates this state by becoming true.

Freezing objects can improve performance because they no longer need to be monitored for changes. A frozen Freezable object can also be shared across threads, while an unfrozen Freezable object cannot. Although you cannot unfreeze a frozen object, you can make an unfrozen copy of it.

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.1    // Freeze this object, making it read-only (since we don't plan on changing it)

if (theBrush.CanFreeze)
theBrush.Freeze();

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.

No comments:

Post a Comment