Skip to content

Bug: SynchronizationContext is not set for secondary views in a UWP app #2288

@benstevens48

Description

@benstevens48

Description

SynchronizationContext.Current is null for any secondary application views (created by CoreApplication.CreateNewView()) in a UWP app using CsWinRT. This means after awaiting most async methods from the UI thread of a secondary view, trying to set a control property crashes due to being on the wrong thread. It seems the workaround is to use the Windows.System.DispatcherQueueSynchronizationContext type provided by CsWinRT as follows when setting up the view. However, I couldn't find this documented anywhere.

 await newView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
 {
     var context = new DispatcherQueueSynchronizationContext(DispatcherQueue.GetForCurrentThread());
     SynchronizationContext.SetSynchronizationContext(context);
     //...

Is this a bug or is it a necessary workaround that needs documenting? This just worked by default with the old .Net Native toolchain.

PS the SynchronizationContext for the main thread is correctly set to Windows.System.DispatcherQueueSynchronizationContext in the generated main function.

Steps To Reproduce

See description

Expected Behavior

No crash

Version Info

CsWinRT 2.2, Windows 25H2, UWP.

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentation

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions