简体   繁体   中英

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?'

When attempting to call a single-threaded apartment (STA) function from the "wrong" thread ( eg , Clipboard::SetContent(...) ), I see the following message:

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

It's not obvious which functions are STA, so it just seems to jump out from seemingly innocent-looking functions. I couldn't find a simple answer that explains the steps to fix it. The Windows COM documentation is difficult to follow.

How can I reliably identify what is a STA function in order to prevent this error? Isn't there a simple fix?

The problem is that the thread you're currently running on is MTA (multi-threaded apartment), and doesn't support STA calls.

The fix is to dispatch the call from the main/UI thread, which is always STA and therefore supports STA calls.

First, get the thread you want with MainView->CoreWindow , and then call that thread's dispatcher to invoke whatever it was you wanted to run. For example:

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);
        }
   )
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM