0

When attempting to call a single-threaded apartment (STA) function from the "wrong" thread (e.g., 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?

Katie
  • 51
  • 7
Andy Krouwel
  • 1,309
  • 11
  • 21
  • 1
    Quote: "This class is not agile, which means that you need to consider its threading model and marshaling behavior. For more info, see ...". Maybe it sounds gobbledegooky but after a while you'll see the connection between the docs and the exception. With the link in the "see" note telling you what to do about it. – Hans Passant Oct 12 '17 at 14:46
  • Yes, I waded through all of that which is how I came up with the answer below. The point of adding this question was to spare others that trauma when they tread on the STA/MTA landmine. – Andy Krouwel Oct 13 '17 at 07:52

1 Answers1

0

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);
        }
   )
);
Katie
  • 51
  • 7
Andy Krouwel
  • 1,309
  • 11
  • 21
  • If you h ave resolved your issue please mark it as accepted to convenient people who visit this thread later, Thanks for understanding. – Sunteen Wu Oct 26 '17 at 03:15