microsoft / CsWinRT

C# language projection for the Windows Runtime
MIT License
554 stars 107 forks source link

DispatcherQueue doesn't flow the .NET ExecutionContext #1345

Open jlaanstra opened 1 year ago

jlaanstra commented 1 year ago

Describe the bug DispatcherQueue doesn't flow the .NET ExecutionContext like other built-in classes in .NET do, see https://devblogs.microsoft.com/pfxteam/executioncontext-vs-synchronizationcontext/

In UWP this is at least done by https://github.com/dotnet/corefx/blob/1814a950a4ed69da659d34ed5329e2eabd59b3cc/src/System.Runtime.WindowsRuntime/src/System/Threading/WindowsRuntimeSynchronizationContext.cs#L179

However, one could argue that was still incomplete as this should really be done for any managed callback passed into https://learn.microsoft.com/en-us/windows/windows-app-sdk/api/winrt/microsoft.ui.dispatching.dispatcherqueue.tryenqueue?view=windows-app-sdk-1.3#microsoft-ui-dispatching-dispatcherqueue-tryenqueue(microsoft-ui-dispatching-dispatcherqueuehandler)

Not doing this causes issues with .NET functionality that relies on the ExecutionContext flowing, for example using AsyncLocal, like https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.activity.current?view=net-7.0

To Reproduce N/A

Expected behavior ExecutionContext should be captured and flow across DispatcherQueue.TryEnqueue like it does for Task.Run, for ThreadPool.QueueUserWorkItem etc.

Version Info CsWinRT 2.0.3

Additional context Filing this here for visibility but I think the projection for DispatcherQueue isn't coming from here. However this equally applies to https://learn.microsoft.com/en-us/uwp/api/windows.system.threading.threadpool.runasync?view=winrt-22621 which I believe is projected here.

Scottj1s commented 1 year ago

Note: this isn't a C#/WinRT issue, but a Microsoft.UI.Dispatching issue. Any customization of the DispatcherQueue projection would need to be done by the Microsoft.UI.Dispatching team, just as they've provided a pure C# implementation of DispatcherQueueSyncContext. This is compiled along with remaining "generic" Microsoft.UI.Dispatching projection sources into Microsoft.InteractiveExperiences.Projection.dll, distributed with Windows App SDK.

That said, I don't see any issue with your request. As noted here, In .NET Core, synchronization context no longer flows with execution context, as it did with NetFX. So the pathological concerns described in ExecutionContext vs SynchronizationContext shouldn't be a concern.