WinRT : Why there is no need of un-initializing the apartment after initializing it?

Harshithraj1871 1,516 Reputation points
2024-01-19T16:13:49.5+00:00

Hi,

I'm building winui3 desktop app in pure c++ without XAML files. In the beginning, I'm initializing the thread with Single Threaded Apartment with init_apartment . But I did not find any documentation that says we need to un initialize it. Why don't we have to un initialize?

As internally it is initializing the COM library, and usually when we Initialize COM lib with CoInitializeEX(), we do a CoUnIntializeEX at the end. So why is un initialization not required for init_apartment?

If I don't make a call to init_apartment with STA, will it set MTA by default?

Thank You.

Windows App SDK
Windows App SDK
A set of Microsoft open-source libraries, frameworks, components, and tools to be used in apps to access Windows platform functionality on many versions of Windows. Previously known as Project Reunion.
747 questions
0 comments No comments
{count} votes

Accepted answer
  1. Xiaopo Yang - MSFT 12,151 Reputation points Microsoft Vendor
    2024-01-24T03:13:51.03+00:00

    For Windows App SDK, “it will get cleaned up when the process dies.” This is also mentioned in the thread about Windows App SDK by Raymond Chen. "The app simply exits and doesn't tear down the frame. This follows the principle of 'When the process is exiting, don't bother cleaning up.' "

    And add that “It's very very rarely a good idea to call CoUninitialize. Tearing down the apartment means that any subsequent destructors can't assume they are running in a valid apartment and they typically do. It's best to just let the process unwind and die without ever calling CoUninitialize unless you are in a highly controlled environment, which is not the case in this kind of project.”

    Also, “The thing about CoInitialize/CoUninitialize is to remember that they aren’t a global process thing; they control the state of COM on a particular thread. For the main application thread, there’s no need to uninit COM as the process is on its way out. In fact, attempting to do so will probably cause more problems, unless you can painstakingly ensure that the uninit will occur after all your other COM-related destructors run (aka global/static objects).

    The main use case that comes to mind for making sure to pair up CoInitialize/CoUninitialize COM calls is for when you are creating and destroying threads. But you rarely, if ever, want to do that yourself. Use the C++/WinRT coroutine+support instead.”

    Further Reading: when the building is being demolished, don’t bother sweeping the floor.


1 additional answer

Sort by: Most helpful
  1. Xiaopo Yang - MSFT 12,151 Reputation points Microsoft Vendor
    2024-01-22T05:10:33.8366667+00:00

    If I don't make a call to init_apartment with STA, will it set MTA by default?

    It's set at auto-generated wWinMain by default. See the question.