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

Shyam Butani 330 Reputation points
2024-11-20T09:42:45.1266667+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::IObservableVector across threads. Specifically, if I create a IObservableVector on one thread (Thread 1) and pass its ABI pointer to another thread (Thread 2), can I safely destroy it on Thread 2?

Here’s the setup:

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

void threadFunc1()
{
    IObservableVector vec = winrt::single_threaded_observable_vector<int>();

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

void threadFunc2()
{
    // Destroy (decrement ref count) on different thread
    ((IUnknown*)ptr)->Release();
}

This code works as expected: I’m able to create the IObservableVector 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.

Universal Windows Platform (UWP)
{count} votes

Accepted answer
  1. Junjie Zhu - MSFT 19,641 Reputation points Microsoft Vendor
    2024-11-21T05:34:08.55+00:00

    Hello @Shyam Butani ,

    winrt::single_threaded_observable_vector is safe to use from a single thread but is not safe to use from multiple threads.you are using it on multiple threads, which is a violation of the rules, and the results are undefined.

    If you want an IObservableVector that is multithread safe, it is recommended to use multi_threaded_observable_vector.

    Thank you.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

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.