CoreDispatcher.RunAsync(CoreDispatcherPriority, DispatchedHandler) 메서드

정의

작업자 스레드에서 UI 스레드에서 제공된 콜백을 예약하고 결과를 비동기적으로 반환합니다.

public:
 virtual IAsyncAction ^ RunAsync(CoreDispatcherPriority priority, DispatchedHandler ^ agileCallback) = RunAsync;
/// [Windows.Foundation.Metadata.RemoteAsync]
IAsyncAction RunAsync(CoreDispatcherPriority const& priority, DispatchedHandler const& agileCallback);
[Windows.Foundation.Metadata.RemoteAsync]
public IAsyncAction RunAsync(CoreDispatcherPriority priority, DispatchedHandler agileCallback);
function runAsync(priority, agileCallback)
Public Function RunAsync (priority As CoreDispatcherPriority, agileCallback As DispatchedHandler) As IAsyncAction

매개 변수

priority
CoreDispatcherPriority

이벤트 디스패치의 우선 순위를 지정합니다. 이를 CoreDispatcherPriority.Normal로 설정합니다.

agileCallback
DispatchedHandler

이벤트가 디스패치될 때 디스패처가 반환하는 콜백입니다.

반환

완료된 비동기 이벤트 디스패치에 대한 처리기를 제공하는 개체입니다.

특성

예제

다음 예제에서는 Dispatcher.RunAsync를 사용하여 CoreWindow의 이벤트 디스패처를 사용하여 기본 UI 스레드에서 작업을 예약하는 방법을 보여 줍니다.

await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
   rootPage.NotifyUser("The toast encountered an error", NotifyType.ErrorMessage);
});

var ignored = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
   Scenario3OutputText.Text += outputText;
});
TimerTextBlock().Dispatcher().RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, [=]()
{
    ++m_count;
    std::wstringstream wstringstream;
    wstringstream << L"Total count: " << m_count;
    TimerTextBlock().Text(wstringstream.str().c_str());
});
// 
_Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, 
                     ref new Windows::UI::Core::DispatchedHandler([this]()
{
  _count++;
  TimerTextBlock->Text = "Total Running Time: " + _count.ToString() + " Seconds";
}));

// using CallbackContext::Any
void Playback::DisplayStatus(Platform::String^ text)
{
  _Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, 
                        ref new Windows::UI::Core::DispatchedHandler([=]()
  {
    _OutputStatus->Text += text + "\n";
  }, CallbackContext::Any)); 
}

설명

작업자 스레드에 있고 UI 스레드에서 작업을 예약하려는 경우 CoreDispatcher.RunAsync를 사용합니다. 항상 우선 순위를 CoreDispatcherPriority.Normal 또는 CoreDispatcherPriority.Low로 설정하고 연결된 콜백이 CoreDispatcherPriority.Normal 또는 CoreDispatcherPriority.Low도 사용하는지 확인합니다.

참고

CoreDispatcherPriority.Low 우선 순위로 예약된 콜백은 보류 중인 입력 이벤트가 없을 때 호출됩니다. CoreDispatcherPriority.Low 우선 순위를 사용하여 앱 UI의 응답성을 높입니다. 백그라운드 작업을 예약하려면 CoreDispatcher.RunIdleAsync를 사용합니다.

UI 스레드에서 작업자 스레드를 스핀오프하려면 이 메서드(CoreDispatcher.RunAsync)를 사용하지 마세요. 대신 Windows.System.Threading.ThreadPool.RunAsync 메서드 오버로드 중 하나를 사용합니다.

이 메서드는 CoreDispatcher가 종료되기 시작하지만 UI 스레드에서 지정된 콜백을 실행하지 않을 때 성공적으로 완료됩니다. 이 사례를 검색해야 하는 경우 CoreDispatcher.TryRunAsync 를 사용합니다.

C++/WinRT. CoreDispatcher.RunAsync의 대안은 winrt::resume_foreground.

백그라운드 스레드에서 보낸 UI 작업 대기

RunAsync를 호출하여 백그라운드 스레드에서 UI를 업데이트하면 UI 스레드에서 작업을 예약하고 호출자에게 컨트롤을 즉시 반환합니다. 반환하기 전에 비동기 작업이 완료되기를 기다려야 하는 경우(예: 대화 상자에서 사용자 입력을 기다리는 경우 ) RunAsync 만 사용하지 마세요. 또한 RunAsync 는 태스크가 호출자에게 결과를 반환하는 방법을 제공하지 않습니다.

이 C# 예제에서 RunAsync 는 대화 상자에서 사용자 입력을 기다리지 않고 를 반환합니다. (RunAsync람다 식 의 코드가 실행되기 시작하는 즉시 를 반환합니다.)

//DO NOT USE THIS CODE.

await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
   await signInDialog.ShowAsync(); 
});
// Execution continues here before the call to ShowAsync completes.

이 경우 C#의 경우 RunAsync와 함께 TaskCompletionSource 를 사용하여 백그라운드 스레드에서 대기할 수 있는 작업을 반환하여 UI 작업이 완료될 때까지 실행을 일시 중지해야 합니다.

public async Task<ContentDialogResult> SignInAsync()
{
    TaskCompletionSource<ContentDialogResult> taskCompletionSource = 
        new TaskCompletionSource<ContentDialogResult>();

    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
    {
        try
        {
            taskCompletionSource.SetResult(await signInDialog.ShowAsync());
        }
        catch (Exception ex)
        {
            taskCompletionSource.SetException(ex);
        }
    });

    return await taskCompletionSource.Task;
}

이를 위해 작업 코드 조각 라이브러리의 RunTaskAsync 확장 메서드 를 사용하는 것이 좋습니다. 백그라운드 스레드에서 실행되는 코드가 UI 스레드에서 실행되어야 하는 작업을 대기할 수 있도록 하는 강력한 솔루션을 제공합니다. 코드 및 사용 예제 는 백그라운드 스레드에서 보낸 UI 작업 대기 페이지를 참조하세요.

C++/WinRT. TaskCompletionSource 는 C++/WinRT에서 사용할 수 없습니다. 대체 옵션은 완료 원본 샘플을 참조하세요.

.NET에서 포팅

.NET 코드에서 포팅하고 Dispatcher.BeginInvokeDispatcher.Invoke 메서드를 사용하는 경우 CoreDispatcher.RunAsync 는 비동기입니다. 동기 버전이 없습니다. Dispatcher.InvokeCoreDispatcher.RunAsync로 변경한 후 코드는 Windows 런타임 비동기 패턴을 지원하고 선택한 언어에 특정 람다 구문을 사용해야 합니다.

적용 대상

추가 정보