microsoft / WindowsAppSDK

The Windows App SDK empowers all Windows desktop apps with modern Windows UI, APIs, and platform features, including back-compat support, shipped via NuGet.
https://docs.microsoft.com/windows/apps/windows-app-sdk/
MIT License
3.8k stars 320 forks source link

Copy from a XAML control crashes with RPC_WRONG_THREAD / "Activating a single-threaded class from MTA is not supported" #4615

Closed zadjii-msft closed 1 month ago

zadjii-msft commented 1 month ago

I'm adding my own notes here, so they're searchable.

I had followed Making the app single-instanced (Part 3) to make my C# WinAppSDK app single-instanced. Part of that blog makes the Main async. So it looked like this:

    // kids, don't try this at home
    [STAThread]
    static async Task<int> Main(string[] args)
    {

Then I added a Windows Community Toolkit MarkdownTextBlock. I set IsTextSelectionEnabled="True" on that text block. When I went to copy text from that text block, I'd always crash, with

MyApp.App.InitializeComponent.AnonymousMethod__7_2(object sender, Microsoft.UI.Xaml.UnhandledExceptionEventArgs e) Line 75  C#
  Microsoft.WinUI.dll!WinRT._EventSource_global__Microsoft_UI_Xaml_UnhandledExceptionEventHandler.EventState.GetEventInvoke.AnonymousMethod__1_0(object sender, Microsoft.UI.Xaml.UnhandledExceptionEventArgs e)  Unknown
  Microsoft.WinUI.dll!ABI.Microsoft.UI.Xaml.UnhandledExceptionEventHandler.Do_Abi_Invoke(nint thisPtr, nint sender, nint e)  Unknown
  [Native to Managed Transition]  
  [Managed to Native Transition]  
  Microsoft.WinUI.dll!ABI.Microsoft.UI.Xaml.IApplicationStaticsMethods.Start(WinRT.IObjectReference _obj, Microsoft.UI.Xaml.ApplicationInitializationCallback callback)  Unknown
Name Value Type
Message "Activating a single-threaded class from MTA is not supported\r\n\r\nActivating a single-threaded class from MTA is not supported\r\n" string

Turns out, async Mains are considered harmful. Not only that, but doing this would have also broken Narrator.

As it also turns out, the actual samples repo doesn't make Main async either! https://github.com/microsoft/WindowsAppSDK-Samples/blob/ba29b02e9f529baea5e3015f7cb224a5c8447e6a/Samples/AppLifecycle/Instancing/cs2/cs-winui-packaged/CsWinUiDesktopInstancing/CsWinUiDesktopInstancing/Program.cs#L29-L33

zadjii-msft commented 1 month ago

Big thanks to everyone internally who helped point me in the right direction ☺️