Home > Blockchain >  Is CoInitialize() always implicitly called on every .Net Framework / .Net Core thread?
Is CoInitialize() always implicitly called on every .Net Framework / .Net Core thread?

Time:11-28

There are those [MTAThread] and [STAThread] attributes which control the apartment threading model for COM in .Net applications, and from my own (very limited) testing, CoInitializeEx() returns 1 (S_FALSE) if called from the main thread of a console C# application.

According to Microsoft documentation, S_FALSE means "The COM library is already initialized on this thread".

What I am wondering is whether there is actually a contractual guarantee in the framework itself that COM is going to be initialized on every .Net (Framework or Core application) thread?

If so, is it also guaranteed that all threads will be initialized with the same (STA or MTA) model?

I am asking this because for DirectShow applications it is crucial that COM is initialized on every thread, and I would like to avoid peppering the code with redundant calls to CoInitializeEx() and CoUnitialize() if those are already implicitly handled by the framework.

CodePudding user response:

The documentation states that threads from the Managed Thread Pool are

in the multithreaded apartment

The documentation for Task.Run() also states that it

Queues the specified work to run on the ThreadPool

(ThreadPool in this case being the Managed Thread Pool.)

Finally, the documentation for class Thread's obsolete ApartmentState property states that

In .NET Framework version 2.0, new threads are initialized as ApartmentState.MTA if their apartment state has not been set before they are started.

That covers pretty much all of the managed ways to create a thread.

You could of course slap an [MTAThread] attribute on your Main() method too, but even that's not necessary because the default for the main entry point is MTA too.

So at the end of the day - unless you're calling any unusual third-party code, you can pretty much be guaranteed that your threads will be MTA.

  • Related