Freezable 개체 개요

이 항목에서는 애플리케이션 성능을 개선하는 데 도움이 될 수 있는 특수 기능을 제공하는 Freezable 개체를 효과적으로 사용하고 만드는 방법을 설명합니다. 고정 가능한 개체의 예로는 브러시, 펜, 변환, 기하 도형, 애니메이션 등이 있습니다.

Freezable이란?

Freezable은 고정 취소 및 고정이라는 두 가지 상태를 가지는 특수한 개체 유형입니다. 고정 취소인 경우 Freezable은 다른 개체처럼 동작하는 것처럼 보입니다. 고정인 경우 Freezable은 더 이상 수정할 수 없습니다.

Freezable은 개체 수정에 관해 관찰자에게 알리는 Changed 이벤트를 제공합니다. Freezable을 고정하면 변경 알림에 더 이상 리소스를 사용할 필요가 없으므로 성능이 향상될 수 있습니다. 또한 고정된 Freezable 은 스레드 간에 공유할 수 있지만 고정 취소된 Freezable 스레드는 공유할 수 없습니다.

Freezable 클래스에는 많은 애플리케이션이 있지만 WPF(Windows Presentation Foundation)의 대부분 Freezable 개체는 그래픽 하위 시스템과 관련이 있습니다.

Freezable 클래스를 사용하면 특정 그래픽 시스템 개체를 더 쉽게 사용할 수 있으며 애플리케이션 성능 향상에 도움이 될 수 있습니다. Freezable에서 상속되는 형식의 예로는 Brush, TransformGeometry 클래스가 있습니다. 해당 형식에는 관리되지 않는 리소스가 포함되므로 시스템에서는 이러한 개체가 수정되는지 모니터링한 다음, 원래 개체가 변경된 경우 해당 관리되지 않는 리소스를 업데이트해야 합니다. 실제로 그래픽 시스템 개체를 수정하지 않더라도 개체를 변경하는 경우 시스템에서는 개체를 모니터링하는 데 일부 리소스를 계속 사용해야 합니다.

예를 들어, SolidColorBrush 브러시를 만들고 단추의 배경을 그리는 데 사용한다고 가정합니다.

Button myButton = new Button();
SolidColorBrush myBrush = new SolidColorBrush(Colors.Yellow);
myButton.Background = myBrush;
Dim myButton As New Button()
Dim myBrush As New SolidColorBrush(Colors.Yellow)
myButton.Background = myBrush

단추가 렌더링되면 WPF 그래픽 하위 시스템은 제공한 정보를 사용하여 단추 모양을 만드는 픽셀 그룹을 그립니다. 단색 브러시를 사용하여 단추를 칠하는 방법을 설명했지만 단색 브러시는 실제로 그리기를 수행하지 않습니다. 그래픽 시스템은 단추와 브러시에 대해 빠른 하위 수준 개체를 생성하며 이 개체가 실제로 화면에 나타납니다.

브러시를 수정하면 해당 하위 수준 개체를 다시 생성해야 합니다. Freezable 클래스는 브러시의 해당하는 생성된 하위 수준 개체를 찾고 브러시가 변경될 때 업데이트하는 기능을 브러시에 제공합니다. 이 기능이 사용되는 경우 브러시를 “고정 취소”라고 합니다.

Freezable의 Freeze 메서드를 사용하면 이 자동 업데이트 기능을 사용하지 않도록 설정할 수 있습니다. 이 메서드를 사용하여 브러시를 “고정” 상태로 설정하거나 수정할 수 없도록 설정할 수 있습니다.

참고

모든 Freezable 개체를 고정할 수 있는 것은 아닙니다. InvalidOperationException throw를 방지하려면 Freezable 개체의 CanFreeze 속성 값을 확인하여 고정을 시도하기 전에 고정할 수 있는지 여부를 확인합니다.

if (myBrush.CanFreeze)
{
    // Makes the brush unmodifiable.
    myBrush.Freeze();
}
If myBrush.CanFreeze Then
    ' Makes the brush unmodifiable.
    myBrush.Freeze()
End If

Freezable을 더 이상 수정할 필요가 없는 경우 개체를 고정하면 성능상 이점이 제공됩니다. 이 예제에서 브러시를 고정하면 그래픽 시스템은 더 이상 개체가 변경되는지 모니터링할 필요가 없습니다. 그래픽 시스템은 브러시가 변경되지 않는다는 것을 알고 있으므로 다른 최적화를 수행할 수도 있습니다.

참고

편의를 위해 명시적으로 고정하지 않는 한 Freezable 개체는 고정 취소로 유지됩니다.

Freezable 사용

고정 취소된 Freezable을 사용하는 것은 다른 유형의 개체를 사용하는 것과 같습니다. 다음 예제에서 SolidColorBrush의 색상은 단추의 배경을 그리는 데 사용된 후 노란색에서 빨간색으로 변경됩니다. 그래픽 시스템은 백그라운드에서 작동하여 다음에 화면을 새로 고칠 때 단추를 노란색에서 빨간색으로 자동으로 변경합니다.

Button myButton = new Button();
SolidColorBrush myBrush = new SolidColorBrush(Colors.Yellow);
myButton.Background = myBrush;

// Changes the button's background to red.
myBrush.Color = Colors.Red;
Dim myButton As New Button()
Dim myBrush As New SolidColorBrush(Colors.Yellow)
myButton.Background = myBrush


' Changes the button's background to red.
myBrush.Color = Colors.Red

Freezable 고정

Freezable을 수정할 수 없도록 설정하려면 해당 Freeze 메서드를 호출합니다. Freezable 개체가 포함된 개체를 고정하면 Freezable 개체도 고정됩니다. 예를 들어, PathGeometry를 고정하면 포함된 수치와 세그먼트도 고정됩니다.

다음에 해당하는 경우에는 Freezable을 고정할 수 없습니다.

  • 애니메이션 효과를 주거나 데이터 바인딩된 속성이 있습니다.

  • 동적 리소스에 의해 설정된 속성이 있습니다. (동적 리소스에 관한 자세한 내용은 XAML 리소스를 참조하세요.)

  • 고정할 수 없는 Freezable 하위 개체가 포함됩니다.

이러한 조건에 해당하지 않고 Freezable을 수정하지 않으려는 경우에는 Freezable을 고정해야 앞에서 설명한 성능 이점을 얻을 수 있습니다.

Freezable의 Freeze 메서드를 호출한 후에는 Freezable을 더 이상 수정할 수 없습니다. 고정된 개체를 수정하려고 하면 InvalidOperationException이 throw됩니다. 다음 코드는 브러시가 고정된 후 브러시를 수정하려고 하기 때문에 예외를 throw합니다.


Button myButton = new Button();
SolidColorBrush myBrush = new SolidColorBrush(Colors.Yellow);

if (myBrush.CanFreeze)
{
    // Makes the brush unmodifiable.
    myBrush.Freeze();
}

myButton.Background = myBrush;

try {

    // Throws an InvalidOperationException, because the brush is frozen.
    myBrush.Color = Colors.Red;
}catch(InvalidOperationException ex)
{
    MessageBox.Show("Invalid operation: " + ex.ToString());
}


Dim myButton As New Button()
Dim myBrush As New SolidColorBrush(Colors.Yellow)

If myBrush.CanFreeze Then
    ' Makes the brush unmodifiable.
    myBrush.Freeze()
End If

myButton.Background = myBrush

Try

    ' Throws an InvalidOperationException, because the brush is frozen.
    myBrush.Color = Colors.Red
Catch ex As InvalidOperationException
    MessageBox.Show("Invalid operation: " & ex.ToString())
End Try

이 예외 throw를 방지하기 위해 IsFrozen 메서드를 사용하여 Freezable이 고정되는지 여부를 확인할 수 있습니다.


Button myButton = new Button();
SolidColorBrush myBrush = new SolidColorBrush(Colors.Yellow);

if (myBrush.CanFreeze)
{
    // Makes the brush unmodifiable.
    myBrush.Freeze();
}

myButton.Background = myBrush;

if (myBrush.IsFrozen) // Evaluates to true.
{
    // If the brush is frozen, create a clone and
    // modify the clone.
    SolidColorBrush myBrushClone = myBrush.Clone();
    myBrushClone.Color = Colors.Red;
    myButton.Background = myBrushClone;
}
else
{
    // If the brush is not frozen,
    // it can be modified directly.
    myBrush.Color = Colors.Red;
}


Dim myButton As New Button()
Dim myBrush As New SolidColorBrush(Colors.Yellow)

If myBrush.CanFreeze Then
    ' Makes the brush unmodifiable.
    myBrush.Freeze()
End If

myButton.Background = myBrush


If myBrush.IsFrozen Then ' Evaluates to true.
    ' If the brush is frozen, create a clone and
    ' modify the clone.
    Dim myBrushClone As SolidColorBrush = myBrush.Clone()
    myBrushClone.Color = Colors.Red
    myButton.Background = myBrushClone
Else
    ' If the brush is not frozen,
    ' it can be modified directly.
    myBrush.Color = Colors.Red
End If


이전 코드 예제에서 수정 가능한 복사본은 Clone 메서드를 사용하여 고정된 개체로 구성됩니다. 다음 섹션에서는 복제에 대해 자세히 설명합니다.

참고

고정된 Freezable에는 애니메이션 효과를 줄 수 없으므로 애니메이션 시스템은 Storyboard를 사용하여 애니메이션 효과를 주려고 할 때 고정된 Freezable 개체의 수정 가능한 복제본을 자동으로 만듭니다. 복제로 인한 성능 오버헤드를 제거하려면 애니메이션 효과를 주려는 경우 개체를 고정 취소로 유지합니다. 스토리보드를 사용하여 애니메이션 효과를 주는 방법에 관한 자세한 내용은 스토리보드 개요를 참조하세요.

태그에서 고정

태그에 선언된 Freezable 개체를 고정하려면 PresentationOptions:Freeze 특성을 사용합니다. 다음 예제에서 SolidColorBrush는 페이지 리소스로 선언되고 고정됩니다. 그런 다음, 단추의 배경을 설정하는 데 사용됩니다.

<Page 
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:PresentationOptions="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options" 
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  mc:Ignorable="PresentationOptions">

  <Page.Resources>

    <!-- This resource is frozen. -->
    <SolidColorBrush 
      x:Key="MyBrush"
      PresentationOptions:Freeze="True" 
      Color="Red" />
  </Page.Resources>


  <StackPanel>

    <Button Content="A Button" 
      Background="{StaticResource MyBrush}">
    </Button>

  </StackPanel>
</Page>

Freeze 특성을 사용하려면 프레젠테이션 옵션 네임스페이스 http://schemas.microsoft.com/winfx/2006/xaml/presentation/options에 매핑해야 합니다. PresentationOptions는 이 네임스페이스를 매핑하는 데 사용하는 것이 좋은 접두사입니다.

xmlns:PresentationOptions="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options"

일부 XAML 판독기는 이 특성을 인식하지 못하므로 mc:Ignorable 특성을 사용하여 PresentationOptions:Freeze 특성을 무시 가능한 것으로 표시하는 것이 좋습니다.

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="PresentationOptions"

자세한 내용은 mc:Ignorable 특성 페이지를 참조하세요.

Freezable “고정 취소”

일단 고정되면 Freezable을 수정하거나 고정 취소할 수 없습니다. 그러나 Clone 또는 CloneCurrentValue 메서드를 사용하여 고정 취소된 복제본을 만들 수 있습니다.

다음 예제에서는 단추 배경이 브러시를 통해 설정되고 해당 브러시가 고정됩니다. 고정 취소된 복사본은 Clone 메서드를 사용하여 브러시로 구성됩니다. 복제본이 수정되고 단추의 배경을 노란색에서 빨간색으로 변경하는 데 사용됩니다.

Button myButton = new Button();
SolidColorBrush myBrush = new SolidColorBrush(Colors.Yellow);

// Freezing a Freezable before it provides
// performance improvements if you don't
// intend on modifying it.
if (myBrush.CanFreeze)
{
    // Makes the brush unmodifiable.
    myBrush.Freeze();
}

myButton.Background = myBrush;

// If you need to modify a frozen brush,
// the Clone method can be used to
// create a modifiable copy.
SolidColorBrush myBrushClone = myBrush.Clone();

// Changing myBrushClone does not change
// the color of myButton, because its
// background is still set by myBrush.
myBrushClone.Color = Colors.Red;

// Replacing myBrush with myBrushClone
// makes the button change to red.
myButton.Background = myBrushClone;
Dim myButton As New Button()
Dim myBrush As New SolidColorBrush(Colors.Yellow)

' Freezing a Freezable before it provides
' performance improvements if you don't
' intend on modifying it. 
If myBrush.CanFreeze Then
    ' Makes the brush unmodifiable.
    myBrush.Freeze()
End If


myButton.Background = myBrush

' If you need to modify a frozen brush,
' the Clone method can be used to
' create a modifiable copy.
Dim myBrushClone As SolidColorBrush = myBrush.Clone()

' Changing myBrushClone does not change
' the color of myButton, because its
' background is still set by myBrush.
myBrushClone.Color = Colors.Red

' Replacing myBrush with myBrushClone
' makes the button change to red.
myButton.Background = myBrushClone

참고

사용하는 복제 메서드에 관계없이 애니메이션은 새 Freezable 메서드에 복사되지 않습니다.

CloneCloneCurrentValue 메서드는 Freezable의 전체 복사본을 생성합니다. Freezable에 다른 고정된 Freezable 개체가 포함된 경우 해당 개체도 복제하고 수정할 수 있습니다. 예를 들어, 고정된 PathGeometry를 복제하여 수정 가능하도록 설정하면 포함된 수치와 세그먼트도 복사되고 수정 가능하도록 설정됩니다.

고유한 Freezable 클래스 만들기

Freezable에서 파생되는 클래스는 다음 기능을 사용할 수 있습니다.

  • 특수 상태: 읽기 전용(고정) 및 쓰기 가능 상태입니다.

  • 스레드 보안: 고정된 Freezable 개체는 스레드 간에 공유할 수 있습니다.

  • 자세한 변경 알림: 다른 DependencyObject와는 다르게 Freezable 개체는 하위 속성 값이 변경될 때 변경 알림을 제공합니다.

  • 쉬운 복제: Freezable 클래스가 이미 전체 복제를 만드는 여러 메서드를 구현 합니다.

FreezableDependencyObject 유형이므로 종속성 속성 시스템을 사용합니다. 클래스 속성은 종속성 속성일 필요가 없지만 Freezable 클래스는 종속성 속성을 고려하여 디자인되었기 때문에 종속성 속성을 사용하면 작성해야 하는 코드의 양이 줄어듭니다. 종속성 속성 시스템에 관한 자세한 내용은 종속성 속성 개요를 참조하세요.

모든 Freezable 서브클래스는 CreateInstanceCore 메서드를 재정의해야 합니다. 클래스가 모든 데이터에 대한 종속성 속성을 사용하는 경우 완료된 것입니다.

클래스에 비종속성 속성 데이터 멤버가 포함된 경우 다음 메서드도 재정의해야 합니다.

종속성 속성이 아닌 데이터 멤버에 액세스하고 쓰려면 다음 규칙도 준수해야 합니다.

  • 비종속성 속성 데이터 멤버를 읽는 API의 시작 부분에서 ReadPreamble 메서드를 호출합니다.

  • 비종속성 속성 데이터 멤버를 쓰는 API의 시작 부분에서 WritePreamble 메서드를 호출합니다. (API에서 WritePreamble을 호출한 후에는 비종속성 속성 데이터 멤버도 읽는 경우 ReadPreamble을 추가로 호출할 필요가 없습니다.)

  • 비종속성 속성 데이터 멤버에 쓰는 메서드를 종료하기 전에 WritePostscript 메서드를 호출합니다.

클래스에 DependencyObject 개체인 비종속성 속성 데이터 멤버가 포함된 경우 해당 멤버를 null로 설정하더라도 해당 값 중 하나를 변경할 때마다 OnFreezablePropertyChanged 메서드를 호출해야 합니다.

참고

기본 구현에 대한 호출로 재정의하는 각 Freezable 메서드를 시작하는 것이 매우 중요합니다.

사용자 지정 Freezable 클래스의 예제는 사용자 지정 애니메이션 샘플을 참조하세요.

참고 항목