microsoft / microsoft/CsWinRT

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

Open
#2,288 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

documentation
Dominant language
C#
Stars
665
Forks
134
Avg merge
1d 3h
Merged PRs (30d)
32

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the secondary-view setup described with CoreApplication.CreateNewView() on CsWinRT 2.2, then compare its SynchronizationContext with the generated main function. Investigate DispatcherQueueSynchronizationContext and the await-to-control-property path; done means establishing whether CsWinRT should set the context automatically or documenting a confirmed workaround, with the crash no longer occurring.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp
Domain
desktop
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
43/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.