CoreDispatcher CoreDispatcher CoreDispatcher Class

Definition

Provides the Windows Runtime core event message dispatcher. Instances of this type are responsible for processing the window messages and dispatching the events to the client.

public sealed class CoreDispatcher : ICoreAcceleratorKeys, ICoreDispatcher, ICoreDispatcher2, ICoreDispatcherWithTaskPrioritypublic sealed class CoreDispatcher : ICoreAcceleratorKeys, ICoreDispatcher, ICoreDispatcher2, ICoreDispatcherWithTaskPriorityPublic NotInheritable Class CoreDispatcher Implements ICoreAcceleratorKeys, ICoreDispatcher, ICoreDispatcher2, ICoreDispatcherWithTaskPriority
Attributes
Windows 10 requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)

Remarks

Instances of this type can be obtained from the CoreWindow.Dispatcher property. The current CoreWindow instance can be obtained by calling CoreWindow.GetForCurrentThread.

void MyCoreWindowEvents::Run() // this is an implementation of IFrameworkView::Run() used to show context. It is called by CoreApplication::Run().
{
    CoreWindow::GetForCurrentThread()->Activate();

    /...

    CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessUntilQuit);
}

Properties

CurrentPriority CurrentPriority CurrentPriority

Gets and sets the priority of the current task.

public CoreDispatcherPriority CurrentPriority { get; set; }public CoreDispatcherPriority CurrentPriority { get; set; }Public ReadWrite Property CurrentPriority As CoreDispatcherPriority
Value
CoreDispatcherPriority CoreDispatcherPriority CoreDispatcherPriority

A CoreDispatcherPriority enumeration value that specifies the priority of the current task.

Attributes

HasThreadAccess HasThreadAccess HasThreadAccess

Gets a value that specifies whether the event dispatcher provided by this instance of CoreWindow has access to the current thread or not.

public bool HasThreadAccess { get; }public bool HasThreadAccess { get; }Public ReadOnly Property HasThreadAccess As bool
Value
bool bool bool

True if the event dispatcher has thread access; false it does not.

Attributes

Methods

ProcessEvents(CoreProcessEventsOption) ProcessEvents(CoreProcessEventsOption) ProcessEvents(CoreProcessEventsOption)

Starts the dispatcher processing the input event queue for this instance of CoreWindow.

public void ProcessEvents(CoreProcessEventsOption options)public void ProcessEvents(CoreProcessEventsOption options)Public Function ProcessEvents(options As CoreProcessEventsOption) As void
Parameters
options
CoreProcessEventsOption CoreProcessEventsOption CoreProcessEventsOption

The options for processing window events.

Attributes

Remarks

This method is called from the main app loop defined in the IFrameworkView::Run method you implemented on your view provider. Typically, you call it once on each iteration of the loop. If you are creating a Windows Store app using DirectX with C++, call this method with CoreProcessEventsOption::ProcessAllIfPending.

If you are using another app model, such as XAML or JavaScript, you do not need to call this method. To avoid reentrancy scenarios in your Windows Store app using C++, C#, or Visual Basic with XAML, use the types and methods in the provided XAML namespaces, which call this method in the appropriate context.

Also, this method fails if called recursively. When it fails, call RoOriginateError to obtain the error and the message supplied to an attached debugger.

RunAsync(CoreDispatcherPriority, DispatchedHandler) RunAsync(CoreDispatcherPriority, DispatchedHandler) RunAsync(CoreDispatcherPriority, DispatchedHandler)

Schedules the provided callback on the UI thread from a worker thread, and returns the results asynchronously.

public IAsyncAction RunAsync(CoreDispatcherPriority priority, DispatchedHandler agileCallback)public IAsyncAction RunAsync(CoreDispatcherPriority priority, DispatchedHandler agileCallback)Public Function RunAsync(priority As CoreDispatcherPriority, agileCallback As DispatchedHandler) As IAsyncAction
Parameters
priority
CoreDispatcherPriority CoreDispatcherPriority CoreDispatcherPriority

Specifies the priority for event dispatch. Set this to CoreDispatcherPriority::Normal.

agileCallback
DispatchedHandler DispatchedHandler DispatchedHandler

The callback on which the dispatcher returns when the event is dispatched.

Returns

The object that provides handlers for the completed async event dispatch.

Attributes

Remarks

If you are on a worker thread and want to schedule work on the UI thread, use CoreDispatcher::RunAsync. Always set the priority to CoreDispatcherPriority::Normal or CoreDispatcherPriority::Low, and ensure that any chained callbacks also use CoreDispatcherPriority::Normal or CoreDispatcherPriority::Low.

Note

Callbacks scheduled with CoreDispatcherPriority::Low priority are called when there are no pending input events. Use the CoreDispatcherPriority::Low priority to make your app UI more responsive. To schedule background tasks, use CoreDispatcher::RunIdleAsync.

To spin off a worker thread from the UI thread, do not use this method (CoreDispatcher::RunAsync ). Instead, use one of the Windows::System::Threading::ThreadPool::RunAsync method overloads.

Await a UI task sent from a background thread

When you update your UI from a background thread by calling RunAsync, it schedules the work on the UI thread and returns control to the caller immediately. If you need to wait for async work to complete before returning, for example, waiting for user input in a dialog box, do not use RunAsync alone. RunAsync also does not provide a way for the task to return a result to the caller.

In this example, RunAsync returns without waiting for the user input from the dialog box. (RunAsync returns as soon as the code in the lambda expression begins executing.)

//DO NOT USE THIS CODE.

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

In this case, you need to use a TaskCompletionSource in combination with RunAsync to return a Task that you can await from your background thread, thereby pausing execution until the UI task completes. We recommend that you use the RunTaskAsync extension method from our task snippet library for this. It provides a robust solution that enables code running on a background thread to await a task that must run on the UI thread. See the Await a UI task sent from a background thread page for the code and example usage.

Porting from .NET

If you are porting from .NET code and using Dispatcher.BeginInvoke and Dispatcher.Invoke methods, note that CoreDispatcher::RunAsync is asynchronous. There is no synchronous version. After you change Dispatcher.Invoke to CoreDispatcher::RunAsync, your code must support the Windows Runtimeasync pattern and use the specific lambda syntax for your chosen language.

Examples

The following examples demonstrate the use of CoreDispatcher::RunAsync to schedule work on the main UI thread using the CoreWindow 's event dispatcher.


// 
_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)); 
}
await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
   rootPage.NotifyUser("The toast encountered an error", NotifyType.ErrorMessage);
});

var ignored = dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
   Scenario3OutputText.Text += outputText;
});
See Also

RunIdleAsync(IdleDispatchedHandler) RunIdleAsync(IdleDispatchedHandler) RunIdleAsync(IdleDispatchedHandler)

Schedules a callback on the UI thread from a worker thread at idle priority, and returns the results asynchronously.

public IAsyncAction RunIdleAsync(IdleDispatchedHandler agileCallback)public IAsyncAction RunIdleAsync(IdleDispatchedHandler agileCallback)Public Function RunIdleAsync(agileCallback As IdleDispatchedHandler) As IAsyncAction
Parameters
agileCallback
IdleDispatchedHandler IdleDispatchedHandler IdleDispatchedHandler

The callback on which the idle priority dispatcher returns when the event is dispatched.

Returns

Object that contains the results of the asynchronous action.

Attributes

Remarks

The RunIdleAsync method is very similar to CoreDispatcher::RunAsync, except that it always schedules the work item at CoreDispatcherPriority::Low priority. When you schedule a work item by calling RunIdleAsync from a worker thread, the work item is processed only when there are no event messages pending in the queue. This allows your app to perform tasks such as spell check or other discrete processing while the system is idle. If the IdleDispatchedHandler delegate returned by the callback has the IsDispatcherIdle property set to false, the work item immediately exits background processing until the event queue is empty again.

However, while your app is processing a background task, it can continue processing as long as there are no event messages pending in the CoreDispatcher event message queue. If your app receives an event message in the queue, then it must break out of the background processing. To determine when your app must exit background processing, access the IsDispatcherIdle property on the IdleDispatchedHandlerArgs object returned by the IdleDispatchedHandler callback you provided to RunIdleAsync. If there is a message, exit background processing and set the priority to CoreDispatcherPriority::Normal. Otherwise, if the callback continues to run without checking the dispatcher status, it could lead to input starvation.

ShouldYield() ShouldYield() ShouldYield()

Queries whether the caller should yield if there are items in the task queue of higher priority than the current task.

public bool ShouldYield()public bool ShouldYield()Public Function ShouldYield() As bool
Returns
bool bool bool

true if the current work item should yield to higher priority work; false if it should not.

Attributes

ShouldYield(CoreDispatcherPriority) ShouldYield(CoreDispatcherPriority) ShouldYield(CoreDispatcherPriority)

Queries whether the caller should yield if there are items in the task queue of the specified priority or higher.

public bool ShouldYield(CoreDispatcherPriority priority)public bool ShouldYield(CoreDispatcherPriority priority)Public Function ShouldYield(priority As CoreDispatcherPriority) As bool
Parameters
priority
CoreDispatcherPriority CoreDispatcherPriority CoreDispatcherPriority

The minimum priority level for which the current work item should yield.

Returns
bool bool bool

true if the current work item should yield to higher priority work; false if it should not.

Attributes

StopProcessEvents() StopProcessEvents() StopProcessEvents()

Stops the dispatcher from processing any queued events.

public void StopProcessEvents()public void StopProcessEvents()Public Function StopProcessEvents() As void
Attributes

TryRunAsync(CoreDispatcherPriority, DispatchedHandler) TryRunAsync(CoreDispatcherPriority, DispatchedHandler) TryRunAsync(CoreDispatcherPriority, DispatchedHandler)

Attempts to schedule the provided callback on the UI thread from a worker thread, and returns the results asynchronously.

public IAsyncOperation<bool> TryRunAsync(CoreDispatcherPriority priority, DispatchedHandler agileCallback)public IAsyncOperation<bool> TryRunAsync(CoreDispatcherPriority priority, DispatchedHandler agileCallback)Public Function TryRunAsync(priority As CoreDispatcherPriority, agileCallback As DispatchedHandler) As IAsyncOperation( Of bool )
Parameters
priority
CoreDispatcherPriority CoreDispatcherPriority CoreDispatcherPriority

Specifies the priority for event dispatch. Set this to CoreDispatcherPriority::Normal.

agileCallback
DispatchedHandler DispatchedHandler DispatchedHandler

The callback on which the dispatcher returns when the event is dispatched.

Returns

The asynchronous operation.

Attributes

TryRunIdleAsync(IdleDispatchedHandler) TryRunIdleAsync(IdleDispatchedHandler) TryRunIdleAsync(IdleDispatchedHandler)

Attempts to schedule a callback on the UI thread from a worker thread at idle priority, and returns the results asynchronously.

public IAsyncOperation<bool> TryRunIdleAsync(IdleDispatchedHandler agileCallback)public IAsyncOperation<bool> TryRunIdleAsync(IdleDispatchedHandler agileCallback)Public Function TryRunIdleAsync(agileCallback As IdleDispatchedHandler) As IAsyncOperation( Of bool )
Parameters
agileCallback
IdleDispatchedHandler IdleDispatchedHandler IdleDispatchedHandler

The callback on which the idle priority dispatcher returns when the event is dispatched.

Returns

The asynchronous operation.

Attributes

Events

AcceleratorKeyActivated AcceleratorKeyActivated AcceleratorKeyActivated

Fired when an accelerator key is activated (pressed or held down).

public event TypedEventHandler AcceleratorKeyActivatedpublic event TypedEventHandler AcceleratorKeyActivatedPublic Event AcceleratorKeyActivated
Attributes

Remarks

** behavior**

XAML processes CTRL+TAB or CTRL+SHIFT+TAB key presses for tab navigation, and apps do not get a chance to handle them from the AcceleratorKeyActivated event. Starting in Windows 8.1, we will allow the tab navigation processing with CTRL+TAB or ALT+TAB or SHIFT+TAB.

If you handled the AcceleratorKeyActivated event in Windows 8 to do special processing, the event will get fired for Tab keys when invoked with CTRL, ALT, or SHIFT modifiers in Windows 8.1. Verify tab navigation with CTRL+TAB or ALT+TAB or SHIFT+TAB keys.