当我收到 WinRT/UWP 错误 'Activating a single-threaded class from MTA is not supported?' 时,如何在 C++ 中调用函数

How can I call a function in C++ when I get the WinRT/UWP error 'Activating a single-threaded class from MTA is not supported?'

尝试从 "wrong" 线程调用单线程单元 (STA) 函数时( 例如 Clipboard::SetContent(...)),我看到以下内容留言:

Activating a single-threaded class from MTA is not supported.

哪些功能是STA并不明显,所以它似乎只是从看似无辜的功能中跳出来的。我找不到一个简单的答案来解释修复它的步骤。 Windows COM 文档很难理解。

如何可靠地识别什么是 STA 函数以防止出现此错误?没有简单的解决方法吗?

问题是您当前运行正在使用的线程是 MTA(多线程单元),不支持 STA 调用。

解决方法是从 main/UI 线程分派调用,该线程始终是 STA,因此支持 STA 调用。

首先,使用 MainView->CoreWindow 获取您想要的线程,然后调用该线程的调度程序来调用您想要的任何内容 运行。例如:

using namespace Windows::UI::Core;
using namespace Windows::ApplicationModel::Core;
using namespace Windows::ApplicationModel::DataTransfer;

CoreWindow^ window = CoreApplication::MainView->CoreWindow;        
window->Dispatcher->RunAsync(CoreDispatcherPriority::Normal,
    ref new DispatchedHandler
    (
        [wstringForClipboard]
        {
            DataPackage^ clipboardInfo = ref new DataPackage;
            clipboardInfo->SetText(ref new Platform::String(wstringForClipboard.c_str()));
            Clipboard::SetContent(clipboardInfo);
        }
   )
);