Can we create and destroy winrt::hstring on different threads?

Shyam Butani 260 Reputation points
2024-11-18T08:50:55.2833333+00:00

Hello,

I’m working on a multi-threaded WinRT/C++ application and need some clarification on how thread safety works when using winrt::hstring across threads. Specifically, if I create a winrt::hstring on one thread (Thread 1) and pass its ABI pointer to another thread (Thread 2), can I safely destroy the string on Thread 2?

Here’s the setup:

int main ()
{
	// Initialize COM on Main thread
	winrt::init_apartment(apartment_type::single_threaded);
}

void threadFunc1()
{
    winrt::hstring myString = L"Hello, WinRT!";

    ptr = detach_abi(myString);  // Store ABI pointer in ptr
}

void threadFunc2()
{
	// Reconstruct the hstring from ABI pointer
    winrt::hstring myString2(ptr, winrt::take_ownership_from_abi);  
}

This code works as expected: I’m able to create the winrt::hstring on Thread 1 and destroy it on Thread 2. My question is, how does this work under the hood? Is COM initialized for all threads involved, or is there some other mechanism in place that makes this safe?

Thanks in advance for any insights!

Universal Windows Platform (UWP)
{count} vote

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.