다음을 통해 공유


앱 일시 중단 방법(DirectX 및 C++)

이 토픽에서는 시스템에서 UWP(유니버설 Windows 플랫폼) DirectX 앱을 일시 중단할 때 중요한 시스템 상태 및 앱 데이터를 저장하는 방법을 보여 줍니다.

일시 중단 이벤트 처리기 등록

먼저 사용자 또는 시스템 작업에 의해 앱이 일시 중단 상태로 이동될 때 발생하는 CoreApplication::Suspending 이벤트를 처리하도록 등록합니다.

이 코드를 뷰 공급자의 IFrameworkView::Initialize 메서드 구현에 추가합니다.

void App::Initialize(CoreApplicationView^ applicationView)
{
  //...
  
    CoreApplication::Suspending +=
        ref new EventHandler<SuspendingEventArgs^>(this, &App::OnSuspending);

  //...
}

일시 중단하기 전에 앱 데이터 저장

앱이 CoreApplication::Suspending 이벤트를 처리할 경우, 해당 이벤트의 중요한 애플리케이션 데이터를 처리기 함수에 저장할 수 있습니다. 이 앱은 LocalSettings 스토리지 API를 사용하여 간단한 애플리케이션 데이터를 동기적으로 저장해야 합니다. 게임을 개발하는 경우 중요한 게임 상태 정보를 저장합니다. 오디오 처리를 일시 중단하는 것을 잊지 마세요!

이제, 콜백을 구현합니다. 이 메서드에 앱 데이터를 저장합니다.

void App::OnSuspending(Platform::Object^ sender, SuspendingEventArgs^ args)
{
    // Save app state asynchronously after requesting a deferral. Holding a deferral
    // indicates that the application is busy performing suspending operations. Be
    // aware that a deferral may not be held indefinitely. After about five seconds,
    // the app will be forced to exit.
    SuspendingDeferral^ deferral = args->SuspendingOperation->GetDeferral();

    create_task([this, deferral]()
    {
        m_deviceResources->Trim();

        // Insert your code here.

        deferral->Complete();
    });
}

이 콜백은 5초로 완료해야 합니다. 이 콜백 중에는 카운트다운을 시작하는 SuspendingOperation::GetDeferral을 호출하여 지연을 요청해야 합니다. 앱이 저장 작업을 완료하면 SuspendingDeferral::Complete를 호출하여 이제 앱이 일시 중단될 준비가 되었음을 시스템에 알릴 수 있습니다. 지연을 요청하지 않거나 앱이 데이터를 저장하는 데 5초 이상 걸리는 경우 앱이 자동으로 일시 중단됩니다.

이 콜백은 앱의 CoreWindow에 대해 CoreDispatcher에서 처리하는 이벤트 메시지로 발생합니다. 앱의 기본 루프(보기 공급자의 IFrameworkView::Run 메서드에서 구현됨)에서 CoreDispatcher::ProcessEvents를 호출하지 않으면 이 콜백이 호출되지 않습니다.

// This method is called after the window becomes active.
void App::Run()
{
    while (!m_windowClosed)
    {
        if (m_windowVisible)
        {
            CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);

            m_main->Update();

            if (m_main->Render())
            {
                m_deviceResources->Present();
            }
        }
        else
        {
            CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
        }
    }
}

Call Trim()

Windows 8.1부터 모든 DirectX UWP 앱은 일시 중단 시 IDXGIDevice3::Trim을 호출해야 합니다. 이 호출은 앱에 할당된 모든 임시 버퍼를 해제하도록 그래픽 드라이버에 지시하여 일시 중단 상태에 있는 동안 메모리 리소스를 회수하기 위해 앱이 종료될 가능성을 줄입니다. 이는 Windows 8.1의 인증 요구 사항입니다.

void App::OnSuspending(Platform::Object^ sender, SuspendingEventArgs^ args)
{
    // Save app state asynchronously after requesting a deferral. Holding a deferral
    // indicates that the application is busy performing suspending operations. Be
    // aware that a deferral may not be held indefinitely. After about five seconds,
    // the app will be forced to exit.
    SuspendingDeferral^ deferral = args->SuspendingOperation->GetDeferral();

    create_task([this, deferral]()
    {
        m_deviceResources->Trim();

        // Insert your code here.

        deferral->Complete();
    });
}

// Call this method when the app suspends. It provides a hint to the driver that the app 
// is entering an idle state and that temporary buffers can be reclaimed for use by other apps.
void DX::DeviceResources::Trim()
{
    ComPtr<IDXGIDevice3> dxgiDevice;
    m_d3dDevice.As(&dxgiDevice);

    dxgiDevice->Trim();
}

단독 리소스 및 파일 핸들 해제

앱이 CoreApplication::Suspending 이벤트를 처리할 때 단독 리소스 및 파일 핸들을 해제할 수도 있습니다. 전용 리소스 및 파일 핸들을 명시적으로 해제하면 앱이 사용하지 않는 동안 다른 앱으로 액세스할 수 있게 하는 데 도움이 됩니다. 앱이 종료 후 활성화되면 전용 리소스 및 파일 핸들을 열어야 합니다.

설명

사용자가 다른 앱 또는 데스크톱으로 전환할 때마다 시스템이 앱을 일시 중단합니다. 사용자가 이 앱으로 다시 전환할 때마다 시스템이 해당 앱을 다시 시작합니다. 시스템이 앱을 다시 시작할 경우, 변수 및 데이터 구조의 콘텐츠는 시스템이 앱을 일시 중단하기 전과 동일합니다. 시스템은 앱을 중단된 위치에서 정확하게 복원합니다. 따라서 해당 앱은 백그라운드에서 실행 중인 것처럼 사용자에게 표시됩니다.

시스템에서는 앱이 일시 중단된 동안 해당 앱과 그 데이터를 메모리에 저장하려고 시도합니다. 그러나 앱을 메모리에 저장할 리소스가 시스템에 없으면 시스템이 앱을 종료합니다. 사용자가 종료된 일시 중단된 앱으로 다시 전환하면 시스템에서 Activated 이벤트를 보내고 CoreApplicationView::Activated 이벤트에 대한 처리기에서 애플리케이션 데이터를 복원해야 합니다.

시스템은 앱이 종료되는 시기를 앱에 알리지 않습니다. 그러므로 앱을 통해 애플리케이션 데이터를 저장하고, 일시 중단될 때 전용 리소스 및 파일 핸들을 해제했다가 종료 후 앱이 활성화될 때 해당 리소스 및 파일 핸들을 복원해야 합니다.