Click or drag to resize
ICanvasAnimatedControlRunOnGameLoopThreadAsync Method
Schedules the provided callback to run asynchronously on the game loop thread.

Namespace:  Microsoft.Graphics.Canvas.UI.Xaml
Assembly:  Microsoft.Graphics.Canvas (in Microsoft.Graphics.Canvas.dll) Version:
IAsyncAction RunOnGameLoopThreadAsync(
	DispatchedHandler agileCallback


Type: Windows.UI.CoreDispatchedHandler

Return Value

Type: IAsyncAction

The action will not run until the control's CreateResources event has completed (including any tracked async actions). This means that the callback can assume that CreateResources has completed.

If the control has not been loaded yet (ie the Loaded event has not been raised) then the IAsyncAction that is returned is in the canceled state. Any work that has not completed before the control has unloaded will also be canceled. This means that any code that uses "await" needs to be able to deal with the possibility that it fails with a TaskCanceledException. If there is no need to wait for the action to complete then the return value can be ignored:

// This might throw TaskCanceledException (as well as any exception thrown by the callback)
await animatedControl.RunOnGameLoopThreadAsync(() => { ... });

// Any exceptions thrown by the callback, including TaskCanceledException, are ignored
var ignoredAction = animatedControl.RunOnGameLoopThreadAsync(() => { ... });

Beware of passing async delegates to this method! The code:

await animatedControl.RunOnGameLoopThreadAsync(async () =>
    await Task.Delay(1000);

might reasonably be expected to print "a", "b", "c", but in fact the output is "a", "c", "b". You may also be surprised to learn that the Debug.WriteLine call which prints "b" will run on an arbitrary threadpool thread, not the game loop thread at all!

For a detailed explanation and solution to these issues, see the GameLoopSynchronizationContext helper which is part of the Example Gallery sample application.

Note that these complexities only occur when the callback passed to RunOnGameLoopThreadAsync is itself async (containing one or more await statements). Everything works straightforwardly with no need for a custom synchronization context as long as your callback is a regular (non async) method or lambda.

See Also